2011-10-14 77 views
0

我想在rails中做一個基本的模型關聯。 基本上我有一個存儲item_id和user_id的List表。Rails的基礎協會

一個用戶可以創建多個「列表項」。

這是正確的方法嗎?

謝謝。

class Item < ActiveRecord::Base 
    has_many :users, :through => :lists 
end 

class User < ActiveRecord::Base 
    has_many :items, :through => :lists 
end 


class List < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :item 
end 
+0

是的,這將工作。或者你可以有Item'belongs_to:list',List'belongs_to:user'和'has_many:items',以及User'has_many:lists'。 –

回答

1

根據您想要達到的目標,您的解決方案是正確的(或不是)。我看到以下情況:

  1. 您想要在項目和用戶之間創建n:m關聯。因此每個項目可以被許多用戶引用,並且每個用戶引用許多項目。如果這是正確的環境,那麼你的解決方案是正確的。有關更多信息,請參閱Rails Guides: Associations
  2. 這種情況的替代方案可能是使用has_and_belongs_to_many Association。情況是一樣的,但談論列表沒有意義,不會有模型對象。
  3. 如果每個用戶可能有很多列表,並且每個列表可能有很多項目,那麼您的解決方案將是錯誤的。這將不是n:m與list之間的連接表,而是兩個1:n關係。

第三例子的代碼看起來像:

class User < ActiveRecord::Base 
    has_many :items, :through => :lists 
    has_many :lists 
end 

class List < ActiveRecord::Base 
    has_many :items 
    belongs_to :user 
end 

class Item < ActiveRecord::Base 
    belongs_to :list 
end 

在第一解決方案,您應該添加爲用戶列表和項目關係到列表:

class Item < ActiveRecord::Base 
    has_many :lists 
    has_many :users, :through => :lists 
end 

class User < ActiveRecord::Base 
    has_many :lists 
    has_many :items, :through => :lists 
end 
0

如果「list」實體確實是一個純關聯/連接,也就是說,它沒有自己的固有屬性,那麼可以簡化一下並使用has_and_belongs_to_many。那麼你不需要一個「List」類。

class Item < ActiveRecord::Base 
    has_and_belongs_to_many :users 
end 

class User < ActiveRecord::Base 
    has_and_belongs_to_many :items 
end 

Rails會查找引用在「items_users」表,所以在遷移,您需要創建它一拉:

create_table :items_users, :id => false do |t| 
    t.references :users, :items 
end 

很多人會告訴你總是使用的has_many:通過,但其他人(像我)會不同意 - 使用正確的工具進行工作。