2

關於使用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行註釋保留我的文檔?

感謝

回答

2

首先檢查attr_accessiblehere你的解釋API文檔。這應該爲您提供更透徹的理解。

其次,您正在使用attr_accessor作爲您不需要的訂單,因爲它是數據庫字段。

最後,您需要在公司模型上設置attr_accessible :workers_attributes。這允許accepts_nested_attributes_for創建的:workers_attributes散列通過質量分配持久。

+0

這完全有效,非常感謝有這麼一段時間的這個問題,並不知道在哪裏看到現在。 – GTDev

+0

不用擔心。在回答問題時,我總是嘗試添加相關的API文檔。他們一直是尋找信息的好地方。 – janders223