0

我有一個名爲Quote的父模型。其中有一個名爲final_quote一個屬性,有一個名爲QuoteBoms子模型,其中有屬性稱爲quote_final_quote和嵌套模型數量和total_quote(= quote_final_quote *量)瞭解Rails中的多態關聯

class Quote < ActiveRecord::Base 
    has_many :quote_boms, dependent: :destroy 
    accepts_nested_attributes_for :quote_boms, :reject_if => :all_blank, :allow_destroy => true 

class QuoteBom < ActiveRecord::Base 
    belongs_to :quote 
    has_many :quotes 
end 

現在,我與聯想選擇報價「belongs_to:報價」,但has_many:報價不起作用,因爲我只有一個quote_id列(我想這是問題)。我看到我需要將第三個類定義爲quotebom_quote_id,但無法弄清楚究竟如何!

任何幫助將不勝感激!

+0

你想用它做什麼?正確解釋 –

+0

嘗試在'QuoteBom'模型中使用'has_and_belongs_to_many:quotes'而不是那兩行。 –

+0

我正在構建一個應用程序,用戶可以在其中爲給定項目製作報價。報價可以通過嵌套模型屬於另一個報價,也可以屬於多個數量。 –

回答

0
class Image < ActiveRecord::Base 
    belongs_to :imageable, :polymorphic => true 
end 
class Profile < ActiveRecord::Base 
    has_many :images, :as => :imageable 
end 
class Article < ActiveRecord::Base 
    has_many :images, :as => :imageable 
end 

這是我們如何做一個圖片模型,它是由一個或多個模型訪問

請參閱本 Link

+0

感謝您的回答,我會盡力並更新! –

+0

感謝您的幫助..非常推崇,我需要的是在quotebom –

0

從我可以告訴你希望創建一個包含模型的數據庫結構Quote和QuoteBom其中Quote有許多QuoteBom和QuoteBom屬於許多行情。

既然如此,您將需要使用has_and_belongs_to_many association

這將需要添加到您的模型

class Quote < ActiveRecord::Base 
    has_and_belongs_to_many :quote_boms 
end 

class QuoteBom < ActiveRecord::Base 
    has_and_belongs_to_many :quotes 
end 

...和以下遷移(假定報價和QuoteBom已經存在)

class CreateQuotesAndQuoteBoms < ActiveRecord::Migration 
    def change 
    create_table :quote_quote_boms, id: false do |t| 
     t.belongs_to :quote, index: true 
     t.belongs_to :quote_bom, index: true 
    end 
    end 
end 

通過在模型中,這具有上述關聯在你的數據庫中,rails會自動處理quote和quote_doms之間的關聯。因此,您也可以訪問您所說的在您的問題中無法完成的quote_dom.quotes。

這是不是一個多態關聯。多態關聯允許模型在單個關聯中屬於多個類型的其他模型。

+0

@hypem另一個foriegn id列,感謝您的回答。我會盡快嘗試。 –

+0

在has_many:through和has_and_belongs_to_many之間選擇..假設我在QuoteBom中有額外的屬性,你會建議使用has_many:而不是has_and_belongs_to_many? –

+0

是的,如果關係需要屬性,回調或驗證,則應該使用具有很多直通關係。 – hypern