【发布时间】:2013-10-29 17:05:39
【问题描述】:
我的 Rails 4 应用中有两个关联模型:product.rb 和 image.rb。 Image 模型允许使用 Paperclip gem 附加文件。
图片belong_to一个产品,一个产品has_many图片。
我想在创建产品时使用产品的new 视图来创建和附加图像。每次我尝试时,与回形针图像相关的参数都不会被保存,最终是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"}
但是,图像实际上并未保存到数据库中。我该如何纠正这个问题?
编辑
仔细查看日志,我发现我收到了“未经许可的参数:图像”错误。即使在我的 product_params 方法中添加了 images_attributes: [:image] 之后也是如此。
【问题讨论】:
-
请问你用的是什么版本的回形针?
-
最新:
gem "paperclip", :git => "git://github.com/thoughtbot/paperclip.git" -
为了将来参考,今天在 github.com/thoughtbot/paperclip 的 HEAD 的提交是 8e900b2a139deff9114efe84e6327235c92e6103。你能确认这是你正在使用的提交吗?它刚刚在 2 天前更新,并且更改相当频繁。谢谢!
-
好点。我在一两次提交后落后于 HEAD。在诊断问题时,出于稳定性考虑,我将使用 3.5.2。
标签: ruby-on-rails-4 paperclip strong-parameters