2009-07-01 61 views
6

這是這個問題的延續: Original Question (SO)導軌 - 雙向的「友誼」模式(續)

回答這個問題涉及以下組模型:

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 

<% for friendship in @user.friendships %> 
    <%= friendship.status %> 
    <%= friendship.friend.firstname %> 
<% end %> 

這可以正常工作,如果說,我有一個用戶,並且我想要在Friendship模型中獲取其id爲user_id FK的所有「友誼」。但是,當我運行像

@user.friendships.friends 

我想它返回所有用戶記錄該用戶要麼是:用戶或:朋友的友誼 - 所以,換句話說,返回所有的友誼在該用戶所涉及的。

希望以上是有道理的。我對Rails仍然很陌​​生,並希望有一種方法可以在不製作標準鏈接表或提供自定義SQL的情況下輕鬆完成此任務。

謝謝!

湯姆

+0

在這裏找到一個很好的答案有一個類似的問題: [與外鍵鏈接表](http://stackoverflow.com/questions/623909/rails-model-with-foreignkey-and-link-table/623956#624261) – Tilendor 2009-07-01 20:16:09

回答

7

railscasts episode

# models/user.rb 
has_many :friendships 
has_many :friends, :through => :friendships 
has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id" 
has_many :inverse_friends, :through => :inverse_friendships, :source => :user 
+0

這看起來很有希望。謝謝。 – cakeforcerberus 2009-07-02 00:33:50

3

你不能只用@ user.friendships這裏,因爲它只會給你之間的友誼,其中@ friendship.user_id == @ user.id。 我現在能想到的唯一的事情就是關於這一主題

1

從railscast鏈接做

Friendship.find_by_user_id(@user.id).concat Friendship.find_by_friend_id(@user.id) 
2

我的解決辦法是AA範圍:

# model 
class Message < ActiveRecord::Base 
    belongs_to :sender, :class_name => "User" 
    belongs_to :recipient, :class_name => "User" 

    scope :of_user, lambda { |user_id| where("sender_id = ? or recipient_id = ?", 
     user_id, user_id) } 
end 


# in controller 
@messages = Message.of_user(current_user) 
+0

這對我有效。簡單而有效。謝謝! – Myxtic 2014-02-09 06:29:50