我有3个型号:
我正在使用devise,paperclip和aws s3创建用户并将图像附加到菜肴上。
问题:菜单正在创建并正确关联到用户,但图像信息未插入dish_image表中,并且在任何地方都看不到任何错误。
我提供了我认为可能需要的代码片段,但如果需要更多信息,请告诉我。
app / models / user.rb
Class User < ActiveRecord::Base
has_many :dishes
app / models / dish.rb
class Dish < ActiveRecord::Base
belongs_to :user, dependent: :delete
has_many :dish_images
accepts_nested_attributes_for :dish_images
app / models / dish_image.rb
class DishImage < ActiveRecord::Base
belongs_to :dish, dependent: :delete
has_attached_file :d_image, styles: {
thumb: '100x100>',
square: '200x200#',
medium: '300x300>'
}
# Validate the attached image is image/jpg, image/png, etc
validates_attachment_content_type :d_image, :content_type => /\Aimage\/.*\Z/
end
我的dish_images_controller.rb文件用于创建读取
def create
@dish = Dish.find(params[:dish_id])
@dish_image = @dish.dishimages.build(dish_image_params)
if @dish_image.save!
flash[:success] = "Image has been uploaded!"
else
flash[:notice] = "Image upload did not work!"
end
end
private
def dish_image_params
params.require(:dish_image).permit(:d_image)
end
上传视图是
%h2 New Dish
= bootstrap_form_for([current_user, @dish], :html => { :multipart => true }) do |f|
%div
= f.text_field :title, autofocus: true
%div
= f.text_field :desc, autofocus: true
%div
= f.fields_for :dish_images do |ff|
Dish Image:
= ff.file_field :d_image, hide_label: true
%div= f.submit "Submit Dish"
和rake路线给出:
user_dish_dishimages GET /users/:user_id/dishes/:dish_id/dishimages(.:format) dishimages#index
POST /users/:user_id/dishes/:dish_id/dishimages(.:format) dishimages#create
user_dish_dishimage DELETE /users/:user_id/dishes/:dish_id/dishimages/:id(.:format) dishimages#destroy
答案 0 :(得分:2)
问题:菜肴正在创建并正确关联到用户,但图像信息未插入 dish_image表,任何地方都没有错误。
首先,提交嵌套表单时,将调用create
的{{1}}操作。要保存dish_images记录,您需要在DishesController
中将dish_images_attributes
列入白名单。
例如:
DishesController
注意:如果您已经有def dish_params
params.require(:dish).permit(:title, :desc, dish_images_attributes: [:id, :d_image])
end
方法将属性列入白名单,则只需更新传递给其中dish_params
的参数即可。如果您的白名单属性方法的名称不是permit
,请相应地更新。