2015-04-27 2 views
0

У меня есть вложенные модели, как, Boat has_many :pictures, Picture belongs_to :boat. Я использовал злой камень, чтобы сделать шаги после того, как пользователь создал лодку. Последним шагом является шаг изображения, где пользователь может перетащить & сбрасывать изображение и т. Д. Он экономит без проблем. Но когда пользователь сбрасывает изображения, он сохраняет и снова отображает страницу (jquery), чтобы показать, что добавлено, поэтому пользователь может уничтожить изображение здесь.Вложенные модели Wicked, render page

Но он отображает страницу с пустыми фотографиями, однако, когда я проверяю базу данных, она сохраняет. Таким образом, это может быть связано с действием boat_steps #show. Но я не мог понять. Поскольку страница с картинками не относится к шагам, путь финиша заканчивается изображением. Но я хотел бы изменить его. Причина, по которой я обновляю страницу, - это то, что я не смог завершить jquery. Это dropzonejs, но если я не буду оставлять комментарии в коде. Я могу удалить фотографию из базы данных, но она хранится на экране.

Вот boat_steps controller

class BoatStepsController < ApplicationController 
    include Wicked::Wizard 


    before_action :logged_in_user 
    steps :model, :pricing, :description, :features, :picture 

    def show #PROBABLY I SHOULD CHANGE HERE 
     @boat = current_user.boats.last 
     @picture = @boat.pictures.new 
     render_wizard 
    end 

    def update 
     @boat = current_user.boats.last 
     @picture = @boat.pictures.new 
     case steps 
      when :picture 
       @picture.update(picture_params) 
       render_wizard @picture 
      else 
      @boat.update(boat_params) 
      render_wizard @boat 
     end 

    end 


private 

    def finish_wizard_path 
     new_boat_picture_path(@boat, @picture) 
    end 



    def boat_params 
     params.require(:boat).permit(:brand, :year, :model, :captained, :boat_type, :daily_price, :boat_length, :listing_tagline, :listing_description, :boat_category, :hull_material, :mast_material, :capacity, :sleeping_capacity, :private_staterooms, :fuel_type, :engine_horsepower, :fuel_capacity, :fuel_consumption, :draft) 
    end 

    def picture_params 
     params.require(:picture).permit(:name, :brand_id, :image) 
    end 


end 

Здесь представлен picture.html.erb

<div class="container"> 

<%= form_for [@boat, @picture], html: { multipart: true, class: "dropzone", id: "picture-dropzone"} do |f| %> 


     <p> 

     <div class="fallback"> 
     <%= f.file_field :image %> 

     </div>  

     </p> 

<% end %> 

<p><%= link_to "Back to My Profile", current_user %></p> 


<% if @pictures.present? %> 
    <% @pictures.each do |pic| %> 
     </br> 
     <%= pic.name %> 
     <%= image_tag pic.image_url(:thumb).to_s %> 
     <%= link_to "edit", edit_boat_picture_path(@boat, pic) %> | 
     <%= link_to 'Destroy', boat_picture_path(@boat, pic), confirm: 'Are you sure?', method: :delete %> | 
     </br> 
    <% end %> 
<% end %> 



<script type="text/javascript"> 
$(document).ready(function(){ 
    // disable auto discover 
    Dropzone.autoDiscover = false; 

    // grap our upload form by its id 
    $("#picture-dropzone").dropzone({ 
     // restrict image size to a maximum 5MB 
     maxFilesize: 5, 
     // changed the passed param to one accepted by 
     // our rails app 
     paramName: "picture[image]", 

     acceptedFiles: "image/*", //CALISIYOR MU BILMIYORUm 
     // show remove links on each image upload 
     addRemoveLinks: false, 
     // if the upload was successful 
     success: function(file, response){ 
      // find the remove button link of the uploaded file and give it an id 
      // based of the fileID response from the server 
      //$(file.previewTemplate).find('.dz-remove').attr('id', response.fileID); 
      //$(file.previewTemplate).find('.dz-remove').attr('boat_id', response.boatID); 
      // add the dz-success class (the green tick sign) 
      $(file.previewElement).addClass("dz-success"); 
      location.reload(); //HERE IT RELOADS THE PAGE 
     }, 
     //when the remove button is clicked 
     //removedfile: function(file){ 

      // grap the id of the uploaded file we set earlier 
     // var id = $(file.previewTemplate).find('.dz-remove').attr('id'); 
     // var boat_id = $(file.previewTemplate).find('.dz-remove').attr('boat_id'); 
     // // make a DELETE ajax request to delete the file 
     // $.ajax({ 
     //  type: 'DELETE', 
     //  url: '/boats/' + boat_id + '/pictures/' + id, 
     //  success: function(file){ 
     //   removeFile(file); 

        //location.reload(); 

     //  } 
     // }); 
     //} 
    }); 
}); 



</script> 

РЕДАКТИРОВАНИЕ 1:

здесь контроллер фото

class PicturesController < ApplicationController 
    before_action :logged_in_user 
    before_filter :load_parent 



    def new 
    @picture = @boat.pictures.new 
    @pictures = @boat.pictures.all 
    end 

    def show 
    @picture = @boat.pictures.find(params[:id]) 
    end 


    def create 

    @picture = @boat.pictures.new(picture_params) 

    if @picture.save 
    render json: { message: "success", fileID: @picture.id, boatID: @boat.id }, :status => 200 

    else 
     render json: { error: @picture.errors.full_messages.join(',')}, :status => 400 

    end 

    end 


    def edit 
    @picture = Picture.find(params[:id]) 
    end 

    def update 
    @picture = @boat.pictures.find(params[:id]) 

    if @picture.update_attributes(picture_params) 
     flash[:notice] = "Successfully updated picture." 
     render 'index' 
    else 
     render 'edit' 
    end 
    end 

    def destroy 

    @picture = @boat.pictures.find(params[:id]) 
    if @picture.destroy 
    #render json: { message: "File deleted from server" } 
     redirect_to new_boat_picture_path(@boat, @picture) 
     flash[:notice] = "Successfully destroyed picture." 
    else 
     render json: { message: @picture.errors.full_messages.join(',') } 
    end 
    #flash[:notice] = "Successfully destroyed picture." 
    #redirect_to new_boat_picture_path(@boat, @picture) 
    #redirect_to boat_pictures_path(@boat) 
    #redirect_to boat_path(@boat) 
    end 




    private 

    def picture_params 
     params.require(:picture).permit(:name, :image) 
    end 

    def load_parent 
    @boat = Boat.find(params[:boat_id]) 
    end 





end 

EDIT 2:

новое шоу-шоу;

def show 
     @boat = current_user.boats.last 
     @picture = @boat.pictures.new 
     @pictures = @boat.pictures.all 

     render_wizard 

    end 

Но тогда, когда я землю на ....boat_steps/picture URL, это показывает некоторые пустые фотографии без нигде. Почему это?

Здесь

enter image description here

ответ

0

В контроллере вы только назначить @picture и по вашему мнению, вы ссылаетесь на @pictures (который не установлен AFAIK).

+0

Если я установил его на @picture, как вы сказали, он выдает ошибку 'undefined method 'each' for # ' – Shalafister

+0

@picture указывает на новую пустую картинку, которую вы используете в форме, @pictures = @ boat.pictures'. Странно, что вы больше не можете читать свой собственный код :) – nathanvda

+0

haha ​​устал немного смотреть на экран. Но теперь он показывает пустые картинки, ничего не делая. Страница приходит как img, которую я загрузил – Shalafister