product.rb
和image.rb
。Image模型使用Paperclip gem附加文件。图片
belong_to
一个产品,而一个产品has_many
Images。我想在创建产品时使用产品的
new
视图来创建和附加图像。每次尝试时,与Paperclip图像相关的参数都无法保存,并最终变成nil
。以下是模型: Product.rb
class Product < ActiveRecord::Base
validates :name, :part_number, presence: true
has_many :images, dependent: :destroy
belongs_to :category
accepts_nested_attributes_for :images, allow_destroy: true
end
Image.rb
class Image < ActiveRecord::Base
belongs_to :product
has_attached_file :image
end
在过去的 Stack Overflow 问题中,我找到了一些相关的问题和答案,但似乎没有任何一个能帮助我的特殊情况。目前为止,我能够使用正确的属性提交文件,但它不会将它们保存到数据库中。
ProductsController#create
def create
@product = Product.new(product_params)
end
def product_params
params.require(:product).permit(:name,
:category_id,
:part_number,
images_attributes: [:image])
end
ProductsController#new
def new
@product = Product.new
@categories = # irrelevant to question
end
products/new.html.haml
= form_for @product, :html =>
= f.label :name
= f.text_field :name
= f.label :part_number
= f.text_field :part_number
= f.label :category_id
= f.select :category_id, @ca
= f.fields_for :image do |ff|
= ff.label :image
= ff.file_field :image
= f.submit('Create Product')
从参数看,我可以确定正确的属性已传递:
示例参数:
{"utf8"=>"✓",
"authenticity_token"=>"jGNy/TasHzP0EcWDFzZ3XH5/fpxb6vD+ncQ2PZSQ3/I=",
"product"=>{"name"=>"bar",
"part_number"=>"foo",
"category_id"=>"30",
"image"=>{
"image"=>#<ActionDispatch::Http::UploadedFile:0x007fc82f58e0e0
@tempfile=#<Tempfile:/var/folders/04/23d9grkj5fv3wkj2t8858kx40000gn/T/RackMultipart20131029-64949-1ldkz4g>,
@original_filename="FPE230_b.jpg",
@content_type="image/jpeg",
@headers="Content-Disposition: form-data; name=\"product[image][image]\"; filename=\"FPE230_b.jpg\"\r\nContent-Type: image/jpeg\r\n">}},
"commit"=>"Create Product"}
然而,这张图片实际上并没有被保存到数据库中。我该怎么解决这个问题?
编辑
仔细查看日志后,我发现我收到了一个“未经许可的参数:image”错误。即使在我的product_params
方法中添加了images_attributes:[:image]
。
gem "paperclip", :git => "git://github.com/thoughtbot/paperclip.git"
- michaelmichael