我的 Rails 4 应用程序中有两个关联的模型:product.rb
and image.rb
。图像模型允许使用回形针 gem 附加文件。
Images belong_to
一个产品,一个产品has_many
Images.
我想使用该产品new
创建产品时查看以创建并附加图像。每次我尝试时,与回形针图像关联的参数都不会保存,并且最终会丢失nil
.
以下是型号:
产品.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"}
但是,图像实际上并未保存到数据库中。我该如何纠正这个问题?
EDIT
更仔细地查看日志,我发现出现了“未经允许的参数:图像”错误。即使添加后也是如此images_attributes: [:image]
to my product_params
method.