Sha*_*mad -4 ruby-on-rails mass-assignment mongoid ruby-on-rails-3
当对/ cloth/create进行POST时,我得到一个警告:无法批量分配受保护的属性:title,description,cloth_type,pic
cloth.rb
class Cloth
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::MultiParameterAttributes attr_accessible :pics
field :title
field :description
field :cloth_type
belongs_to :seller
has_many :pics
attr_accessible :pic_attributes
accepts_nested_attributes_for:pics
end
Run Code Online (Sandbox Code Playgroud)
pic.rb
class Pic
include Mongoid::Document
include Mongoid::Paperclip
has_mongoid_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" },
:storage => :cloud_files,
:cloudfiles_credentials => "#{Rails.root}/config/rackspace.yml",
:path => ":attachment/:id/:timestamp_:style.:extension"
belongs_to :cloth
attr_accessible :cloth_attributes
def create
@cloth = Cloth.create!(params[:cloth])
end
end
Run Code Online (Sandbox Code Playgroud)
答案可以在这里找到:http://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html#method-i-attr_accessible
但是,我会澄清.
通过设置attr_accessible :pic_attributes,您将设置一个白名单,列出可通过质量分配设置的属性.换句话说,你说只有你列出的属性可以通过这样的方式来设置cloth = Cloth.new(params[:cloth]).您要说的任何其他属性都应该使用其访问器来设置,例如cloth.title = params[:title].
如果需要attr_accessible,请将其他属性添加到列表中.
attr_accessible :pic_attributes, :title, :description, etc ...
Run Code Online (Sandbox Code Playgroud)