使用 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