問題描述
Ruby on Rails - Has_many,批量分配問題 (Ruby on Rails - Has_many, Mass Assignment issue)
I'm using rails 3.2.3 and am having issues with mass assignement.
I have a Hotel model and a Hphoto model (integrated with paperclip)
I have tried almost everything and still get mass-assignement error.
Can't mass-assign protected attributes: hphoto
Please take a look.
Hotel model
has_many :hphotos, :dependent=>:destroy
accepts_nested_attributes_for <other models>, :hphotos
attr_accessible: <other attributes>, :hphoto_attributes
Hphoto model
belongs_to :hotel
has_attached_file :photo,
:path => ":rails_root/public/system/:attachment/:id/:style/:filename",
:url => "/system/:attachment/:id/:style/:filename"
attr_accessible :hphoto_attributes
validates_attachment_presence :photo
validates_attachment_size :photo, :less_than => 2.megabytes
validates_attachment_content_type :photo, :content_type=> ['image/jpeg', 'image/png']
My hotel controller:
def new
@hotel = Hotel.new
@hotel.hphotos.build
respond_to do |format|
format.html
format.json { render :json => @hotel }
end
end
def create
@hotel = Hotel.new(params[:hotel])
<original scaffold code>
end
Thanks for your thoughts
參考解法
方法 1:
The statement must use the plural:
attr_accessible: <other attributes>, :hphotos_attributes
On Rails 3.2.3 my erb looks like this:
<%= f.fields_for :hphotos, @hotel.hphotos do |photo_form| %>
<%= photo_form.label :size %>
<%= photo_form.text_field :size %>
<% end %>