我意識到這篇文章是相當古老的,但由於我面臨同樣的問題,爲追隨者添加一些清晰可能會很有趣。正如@ManojMonga在評論中所說,在這裏你需要使用一個has_and_belongs_to_many
關聯。所以車型的樣子:
用戶
has_many :orders, :dependent => :destroy
has_many :products, through: :orders
訂購
belongs_to :user
has_and_belongs_to_many :products
產品
has_and_belongs_to_many :orders
然後,如解釋,您需要創建一個連接表來保存訂單和產品外鍵。遷移是這樣的:
class OrdersProducts < ActiveRecord::Migration
def change
create_table :orders_products, id: false do |t|
t.belongs_to :order, index: true
t.belongs_to :product, index: true
t.timestamps
end
end
end
然後,在你運行遷移後,您就可以使用has_and_belongs_to_many methods。 請記住,當您創建has_an_belongs_to_many關聯中的連接表時,Active Record將查找從按照字母順序連接的2個表名稱命名的表。如果您希望以其他方式命名它,你將不得不在車型將其指定爲以下幾點:
訂購
has_and_belongs_to_many :products, :join_table => "new_tables_name"
產品
has_and_belongs_to_many :orders, :join_table => "new_tables_name"
最後,the has_many :products, through: :orders
在用戶模式ISN是強制性的。它只會允許用戶訪問產品。 就是這樣,如果可以有任何幫助,我會很高興。我正在使用Rails 4.1。
您需要在產品和訂單模型之間有多對多的關係。你可以用'has_and_belongs_to_many'協會,如果你不想使用連接表,否則只有一個選項'的has_many:through' – 2013-02-12 22:11:38
如果我使用HABTM則語義不健全的權利,但我明白你的意思。這看起來像我想要「belongs_to_many」,我認爲它不存在。謝謝你們的幫助。 – maschwenk 2013-02-13 03:46:37
不需要'belongs_to_many',因爲它與現有的'has_many:through'和'HABTM'類似。 'belongs_to'用在我們保持'外鍵'的關聯側。那麼,你如何處理'belongs_to_many'?必須有另一個連接表來處理這種情況,如果是這種情況,那麼可以通過現有的「多對多」關聯來完成。 – 2013-02-13 06:07:53