【问题标题】:Can't mass-assign protected attributes: title, description, cloth_type, pic Rails 3无法批量分配受保护的属性:title、description、cloth_type、pic Rails 3
【发布时间】:2013-01-03 15:30:59
【问题描述】:

对 /cloth/create 进行 POST 时,我收到警告:无法批量分配受保护的属性:标题、描述、布料类型、图片

布料.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

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 mongoid mass-assignment


    【解决方案1】:

    可以在这里找到答案: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 ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-04
      • 1970-01-01
      相关资源
      最近更新 更多