使用mongoid通过嵌套属性进行质量分配的问题。
示例:
require 'mongoid'
require 'mongo'
class Company
include Mongoid::Document
has_many :workers,as: :workable, autosave: true
accepts_nested_attributes_for :workers
end
class Worker
include Mongoid::Document
field :hours, type: Integer, default: 0
belongs_to :workable, polymorphic: true
end
class Manager < Worker
include Mongoid::Document
field :order
#attr_accessible :order
attr_accessor :order
validates_presence_of :order
end
Mongoid.configure do |config|
config.master = Mongo::Connection.new.db("mydb")
end
connection = Mongo::Connection.new
connection.drop_database("mydb")
database = connection.db("mydb")
params = {"company" => {"workers_attributes" => {"0" => {"_type" => "Manager","hours" => 50, "order" => "fishing"}}}}
company = Company.create!(params["company"])
company.workers.each do |worker|
puts "worker = #{worker.attributes}"
end
这输出以下内容:
worker = {"_id"=>BSON::ObjectId('4e8c126b1d41c85333000002'), "hours"=>50, "_type"=>"Manager", "workable_id"=>BSON::ObjectId('4e8c126b1d41c85333000001'), "workable_type"=>"Company"}
如果注释掉了行
attr_accessible :order
我在评论中注释了以下内容:
WARNING: Can't mass-assign protected attributes: _type, hours
worker = {"_id"=>BSON::ObjectId('4e8c12c41d41c85352000002'), "hours"=>0, "_type"=>"Manager", "workable_id"=>BSON::ObjectId('4e8c12c41d41c85352000001'), "workable_type"=>"Company"}
请注意小时值是如何从默认值更新的。
问题,为什么在attr_accessible中评论会弄乱我的文档的持久性。另外我是rails的新手,我不完全理解attr_accessible但我知道我需要它来填写我的视野中的字段。如何使用attr_accessible行注释?
来保持文档的持久性由于
答案 0 :(得分:2)
首先查看API文档,了解有关attr_accessible
here的说明。这应该为您提供更透彻的理解。
其次,您正在使用attr_accessor
作为您不需要的订单,因为它是一个数据库字段。
最后,您需要在公司模型上设置attr_accessible :workers_attributes
。这允许:workers_attributes
创建的accepts_nested_attributes_for
哈希通过批量分配来保留。