我通常在這種情況下規範化數據。
class User
has_many :friendships
has_many :friends
end
class Friendship
belongs_to :user
belongs_to :friend, :class_name => "User"
after_create :reciprocate_friendship
def reciprocate_friendship
return if friend.friends.exists?(user) # do nothing if reciprocal friendship exists
friend.friends << user
end
end
這樣您就可以優化好友查詢。
編輯
如果您必須存儲在一排的朋友關係,然後建立附加關聯添加到User
型號:
has_many :network_friends, :class_name => "User", :finder_sql => Proc.new {
%Q{
SELECT * FROM users
JOIN friendships
ON (users.id = friendships.user_id OR users.id = friendships.friend_id)
WHERE users.id = #{id}
}
}
現在你可以使用新的關聯如下:
user1.friends << user2
user3.friends << user1
user1.network_friends # [ user2, user3]
計算機科學中只有兩件難事... http://laughingmeme.org/2005/12/23/there-are-only-two-hard-東西在計算機科學緩存失效和命名事情/ – phoet