STI和mongoid中的嵌套属性质量分配?
问题描述:
关于使用mongoid通过嵌套属性进行质量分配的问题。STI和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行注释保留我的文档?
感谢
答
首先检查attr_accessible
here你的解释API文档。这应该为您提供更透彻的理解。
其次,您正在使用attr_accessor
作为您不需要的订单,因为它是数据库字段。
最后,您需要在公司模型上设置attr_accessible :workers_attributes
。这允许accepts_nested_attributes_for
创建的:workers_attributes
散列通过质量分配持久。
这完全有效,非常感谢有这么一段时间的这个问题,并不知道在哪里看到现在。 – GTDev
不用担心。在回答问题时,我总是尝试添加相关的API文档。他们一直是寻找信息的好地方。 – janders223