Rails 3.2 を使用しています。と のネストされた属性がshop
ありphoto
ます。にはが含まれphoto
ている必要がありますが、保存すると、が省略/無視されるuser_id
ことを除いてすべてが保存されます。user_id
しかし、update
アクションは完璧に機能します。コードの何が問題になっていますか?
# params[:shop]
{"utf8"=>"✓",
"authenticity_token"=>"AtDD7EgDmX6uBIqdWwD3wwEGFg4tpCx28reWHHN1OmU=",
"shop"=>{"name"=>"SNSD Hotel",
"photos_attributes"=>[{"data"=>#<ActionDispatch::Http::UploadedFile:0x007ffd0449eb58 @original_filename="hotel-spa.jpg",
@content_type="image/jpeg",
@headers="Content-Disposition: form-data; name=\"shop[photos_attributes][][data]\"; filename=\"hotel-spa.jpg\"\r\nContent-Type: image/jpeg\r\n",
@tempfile=#<File:/var/folders/5_/5rfbktcs6398t6kb7d387dr80000gn/T/RackMultipart20130128-2801-107zje1>>,
"user_id"=>1}]},
"commit"=>"Save"}
# spots_controller.rb
def create
@shop = Shop.new(params[:shop])
photos = params[:shop][:photos_attributes]
if !photos.blank?
photos.each do |photo|
photo.merge!(:user_id => current_user.id)
end
end
abort(params[:shop].inspect) # for discussion purpose
if @shop.save
redirect_to shop_path(@shop)
else
render :action => :new
end
end
# shops/_form.html.erb
<%= form_for @shop, :url => { :action => action, :type => type }, :html => { :multipart => true } do |f| %>
<%= f.text_field :name %>
<h3>Pictures</h3>
<%= f.file_field :shop_photos_data, :multiple => true, :name => "shop[photos_attributes][][data]", :accept => "image/*" %><br>
<% end %>
追加モデルコード
# photo.rb
class Photo < ActiveRecord::Base
belongs_to :attachable, :polymorphic => true, :counter_cache => true
belongs_to :user, :counter_cache => true
attr_accessible :data, :attachable_id, :attachable_type, :user_id
end
# shop.rb
class Shop < ActiveRecord::Base
has_many :photos, :as => :attachable, :dependent => :destroy
accepts_nested_attributes_for :photos
end
# user.rb
class User < ActiveRecord::Base
has_many :photos, :as => :attachable, :dependent => :destroy
end