dimanche 15 novembre 2015

Validation failed: Avatar can't be blank

I am working on image uploading in ruby on rails. I used carrierwave gem.

Here is my food image model:

class FoodImage < ActiveRecord::Base
      mount_uploader :avatar, AvatarUploader
      belongs_to :food_item
      validates :avatar, :presence => true
end

and food item model:

class FoodItem < ActiveRecord::Base
      belongs_to :user
      has_many :food_images
      accepts_nested_attributes_for :food_images
... # other irrelevant code

For each food item, user can upload image. The form for uploading an image is in edit.html.haml view of food item (not in the new.html.haml):

= form_tag food_item_path(@food_items), :method => :put do
  ... # other irrelevant code
  = fields_for :food_items, :food_images do
      = label :food_images, :image
      = file_field :food_images, :avatar
      = hidden_field :food_images, :avatar_cache
  ... # other irrelevant code
=  submit_tag 'Update Food Item'

which is passed to the food item update method in food item controller:

def food_item_params
    params.require(:food_items).permit( food_images_attributes:[:id,:post_id,:avatar])
end

def show
    @food_item = FoodItem.find(params[:id])
    @food_image = @food_item.food_images.all
end

def create
    user = User.find(session[:user_id])
    @food_item = user.find_items.build(...)
    @food_item.transaction do
      if @food_item.save
         @food_image = @food_item.food_images.build
      ... # other irrelevant code
 end

def update
    @food_item = FoodItem.find(params[:id])
    @food_item.transaction do
       if @food_item.save
          puts params[:food_images]["avatar"].to_s # for test
          @food_image = @food_item.food_images.create!(:avatar => params[:food_images][:avatar])
       end
    .... # other irrelevant code
 end

When I ran the app, uploaded an image to the file field, and clicked update, it pops the error that 'Avatar can't be blank', which means no image file has been added to database and the validation failed. However, the puts statement above in the update method did print the name of the file. Anyone to check where the bug is?

Aucun commentaire:

Enregistrer un commentaire