Rails 4 アプリには 2 つの関連付けられたモデルがあります:product.rb
とimage.rb
. Image モデルでは、Paperclip gem を使用してファイルを添付できます。
画像belong_to
製品、および製品has_many
画像。
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"}
ただし、画像は実際にはデータベースに保存されていません。どうすればこれを修正できますか?
編集
ログを詳しく見ると、「許可されていないパラメーター: イメージ」エラーが発生していることがわかります。images_attributes: [:image]
これは、私のproduct_params
メソッドに追加した後でもあります。