繼承mongoid文件:填寫使用鑑於以下車型嵌套屬性
class Company
include Mongoid::Document
has_many :workers, autosave: true
accepts_nested_attributes_for :workers
attr_accessible :workers_attributes
end
class Worker
include Mongoid::Document
field :hours
attr_accessible :hours
belongs_to :company
end
class Manager < Worker
field :order
has_many :contributors, :class_name => "Worker"
attr_accessible :order, :contributors
end
class Contributor < Worker
field :task
belongs_to :manager, :class_name => "Worker"
attr_accessible :task
end
如何創建一個使用嵌套屬性在控制器的公司經理和看法?
這裏是我的猜測:
def new
@company = Company.new
@company.workers = [Manager.new]
end
def create
@company = Company.new params[:user]
if @company.save
redirect_to root_url, :notice => "Company with manager created."
else
render :new
end
end
= semantic_form_for @company do |f|
= f.semantic_fields_for :workers do |worker_fields|
= worker_fields.inputs do
= worker_fields.input :hours
= worker_fields.input :order
問題是專門屬於經理後創建不是持久的順序領域。另外,當數據被不正確地填寫有錯誤:
undefined method `order' for #<Worker:0x0000000646f018> (ActionView::Template::Error)
那麼,有沒有一種方式,嵌套屬性從mongoid模型處理繼承?
該問題與Can nested attributes be used in combination with inheritance?有關,除了使用mongoid的活動記錄外。
說實話,這是我的代碼的解釋......真正的代碼是更復雜的情況,雖然我相信這些都是相關的部分。如果你有更多的問題要問。
UPDATE:
我改變了看法以下:
= semantic_form_for @company do |f|
- @company.workers.each do |worker|
- if worker._type == "Manager"
= f.semantic_fields_for :workers, worker do |worker_fields|
= worker_fields.inputs do
= worker_fields.input :hours
= worker_fields.input :order
我沒有得到錯誤了,但是嵌套的屬性不正確地更新公司目標。參數如下:
{"company"=> {"workers_attributes"=>{"0"=>{"hours"=>"30", "order" => "fish", "id"=>"4e8aa6851d41c87a63000060"}}}}
再次編輯簡潔。所以關鍵部分是在「0」=> {data for manager}之間有一個哈希值。工作人員的數據似乎在散列。我希望數據看起來更像如下:
params = { company => {
workers_attributes => [
{ hours => "30", "order" => "fish" }
]}}
因爲工人的數據在陣列中,而不是一個哈希舉行這是不同的。是否有另一個步驟讓嵌套屬性正確保存?
謝謝
好的我更接近解決方案。使用fields_for:workers,worker。將更新問題與我的進展 – GTDev
我想我錯了轉彎。我相信問題變成了可以使用單表繼承的模型使用嵌套屬性進行批量填充 – GTDev