2009-06-22 37 views
11

我試圖創建下面的兩個模式:Rails的 - 如何創建鏈接到另一個模型

User model (this is fine) 

id 

Link model (associated with two Users) 

id 
user_id1 
user_id2 

這是我將要使用的has_and_belongs_to_many關聯類型的鏈路模型實例?我應該怎麼做?

最終,我希望能夠有一個用戶對象,並調用@ user.links獲取涉及該用戶的所有鏈接...

我只是不知道什麼是最好的方式做到這一點在Rails中。

回答

15

你很可能會想要兩個模型結構如下:

class User < ActiveRecord::Base 
    has_many :friendships 
    has_many :friends, :through => :friendships #... 
end 

class Friendship < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :friend, :class_name => 'User', :foreign_key => 'friend_id' 
end 

# ...and hence something like this in your view 
<% for friendship in @user.friendships %> 
    <%= friendship.status %> 
    <%= friendship.friend.firstname %> 
<% end %> 

(這種模式是由Ryan Bates大約兩年前期間this discussionRailsForum發了一個帖子)


剛一張紙條:現在這已經很老了。您可能需要考慮在現代Rails環境中評估其他處理此策略的策略。

+0

真棒,謝謝! – cakeforcerberus 2009-06-22 14:06:30

1

您可以創建一個連接模型,這兩個用戶模型

之間的鏈接關係所以基本上

 

class User 

    has_many :links, :through => :relationships 

end 

class Relationship 

    belongs_to :user_id_1, :class=> "User" 
    belongs_to :user_id_2, :class=> "User" 

end 

相關問題