2

关于使用 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 行让我的文档保持不变?

谢谢

4

1 回答 1

2

首先在attr_accessible 此处查看 API 文档以获取您的解释。这应该可以让你有更透彻的了解。

其次,您正在使用attr_accessor您不需要的订单,因为它是一个数据库字段。

最后,您需要设置attr_accessible :workers_attributes您的公司模型。这允许通过批量分配持久化:workers_attributes由创建的散列。accepts_nested_attributes_for

于 2011-10-05T11:31:35.857 回答