2015-08-25 4 views
0

Я изо всех сил пытался реализовать множественную загрузку с помощью несущей. Мне это удалось, но я заметил, что, хотя другие поля работают правильно, изображения не будут обновляться. Я не могу изменить изображение или удалить ранее загруженные.Rails 4 и Carrierwave - изображение не будет обновляться должным образом

Я совершенно уверен, что что-то делать с моим контроллером, особенно post_params и обновление.

Вот мой контроллер:

class PostsController < ApplicationController 
    before_action :find_posts, only: [:show, :edit, :update, :destroy, :upvote, :downvote] 
    before_action :authenticate_user!, except: [:index, :show, :home] 

    def home 
    end 

    def index 
     if params[:category].blank? 
      @posts = Post.all.order("created_at DESC") 
     else 
      @category_id = Category.find_by(name: params[:category]).id 
      @posts = Post.where(category_id: @category_id).order("created_at DESC") 


     end 
    end 

    def show 
     @inquiries = Inquiry.where(post_id: @post).order("created_at DESC") 
     @random_post = Post.where.not(id: @post).order("RANDOM()").first 
     @post_attachments = @post.post_attachments.all 

    end 

    def new 
     @post = current_user.posts.build 
     @post_attachment = @post.post_attachments.build 
    end 

    def create 
     @post = current_user.posts.build(post_params) 
     respond_to do |format| 
      if @post.save 
       params[:post_attachments]['image'].each do |a| 
        @post_attachment = @post.post_attachments.create!(:image => a) 

       end 
       format.html { redirect_to @post, notice: 'Post was successfully created.' } 
      else 
       format.html { render action: 'new' } 

      end 
     end 
    end 

    def update 
     if @post.update(post_params) 
     params[:post_attachments]['image'].each do |a| 
        @post_attachment = @post.post_attachments.create!(:image => a) 
     flash[:notice] = "Post successfully updated!" 
     redirect_to @post 
     end 
     else 
     flash[:notice] = "Something went wrong...give it another shot!" 
     render 'edit' 
     end 
    end 

    def edit 
    end 



    def destroy 
    @post.destroy 
    respond_to do |format| 
     format.html { redirect_to posts_url, notice: 'Post was successfully destroyed.' } 
     format.json { head :no_content } 
    end 
    end 

    def upvote 
     @post.upvote_by current_user 
     redirect_to @post 
    end 

    def downvote 
     @post.downvote_by current_user 
     redirect_to @post 
    end 

    private 
    def find_posts 
     @post = Post.find(params[:id]) 
    end 

    def post_params 
     params.require(:post).permit(:title, :price, :description, :location, :category_name, :contact_number, post_attachments: []) 
    end 
end 

Моя форма:

.edit-container 
    = simple_form_for @post, html: { multipart: true, class: "dropzone" } do |f| 
     .edit-form 
      = f.input :title 
      = f.input :location, disabled: true 
      = f.input :price 
      = f.input :description 
      = f.input :contact_number, placeholder: "(999) 999-9999" 
      = f.label "Category" 
      = f.text_field :category_name, data: {autocomplete_source: Category.order(:name).map(&:name)}, placeholder: "Choose a category" 
      = f.fields_for :post_attachments do |p| 
       = p.file_field :image, :multiple => true, name: "post_attachments[image][]" 

      = f.button :submit 
%script 
    $('#post_location').val("#{request.location.city}, #{request.location.state}") 

Пример:

Для примера своего поведения сейчас, если я загрузить 3 изображения и попытка editting я получаю это:

enter image description here

Так что, даже если я сохраню все изображения пустыми, когда я отправлю его, он все еще там. Если я хочу только загрузить 1 изображение, оно не изменится.

Я хочу, чтобы он предварительно заполнял изображения ранее загруженными изображениями при редактировании сообщения и менял его на новое изображение, когда я это делаю.

Бонус:

Если вы чувствуете дополнительную полезно сегодня, вы можете помочь мне ходить со мной через реализацию либо Jquery загрузки файлов или Dropzone.js для моей текущей формы (и заставить его работать с моим контроллером). Это было бы здорово.


UPDATE

post_attachment_controller

class PostAttachmentsController < ApplicationController 
    before_action :set_post_attachment, only: [:show, :edit, :update, :destroy] 

    # GET /post_attachments 
    # GET /post_attachments.json 
    def index 
    @post_attachments = PostAttachment.all 
    end 

    # GET /post_attachments/1 
    # GET /post_attachments/1.json 
    def show 
    end 

    # GET /post_attachments/new 
    def new 
    @post_attachment = PostAttachment.new 
    end 

    # GET /post_attachments/1/edit 
    def edit 
    end 

    # POST /post_attachments 
    # POST /post_attachments.json 
    def create 
    @post_attachment = PostAttachment.new(post_attachment_params) 

    respond_to do |format| 
     if @post_attachment.save 
     format.html { redirect_to @post_attachment, notice: 'Post attachment was successfully created.' } 
     format.json { render :show, status: :created, location: @post_attachment } 
     else 
     format.html { render :new } 
     format.json { render json: @post_attachment.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # PATCH/PUT /post_attachments/1 
    # PATCH/PUT /post_attachments/1.json 
    def update 
    respond_to do |format| 
     if @post_attachment.update(post_attachment_params) 
     format.html { redirect_to @post_attachment.post, notice: 'Post attachment was successfully updated.' } 
     format.json { render :show, status: :ok, location: @post_attachment } 
     else 
     format.html { render :edit } 
     format.json { render json: @post_attachment.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # DELETE /post_attachments/1 
    # DELETE /post_attachments/1.json 
    def destroy 
    @post_attachment.destroy 
    respond_to do |format| 
     format.html { redirect_to post_attachments_url, notice: 'Post attachment was successfully destroyed.' } 
     format.json { head :no_content } 
    end 
    end 

    private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_post_attachment 
     @post_attachment = PostAttachment.find(params[:id]) 
    end 

    # Never trust parameters from the scary internet, only allow the white list through. 
    def post_attachment_params 
     params.require(:post_attachment).permit(:post_id, :image) 
    end 
end 
+0

Пожалуйста, покажите свой журнал сервера, когда вы загружаете изображение. Все, начиная с начала действия до конца. –

ответ

0

post_attachments_attributes: [:id, :post_id, :image] Добавить к вашему post_params:

def post_params 
    params.require(:post).permit(:title, :price, :description, :location, :category_name, :contact_number, post_attachments_attributes: [:id, :post_id, :image]) 
end 
+0

Это ничего не делало. Когда я выбираю другое изображение, он просто добавляет, что img для остальных из них, не обновляет его. –

+0

Попробуйте: 'post_attachments_attributes: [: id,: post_id,: image]' –

+0

Ничего. Также есть post_attachments_controller, не могли бы вы взглянуть на это. –

Смежные вопросы