這是這個問題的延續: 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的情況下輕鬆完成此任務。
謝謝!
湯姆
在這裏找到一個很好的答案有一個類似的問題: [與外鍵鏈接表](http://stackoverflow.com/questions/623909/rails-model-with-foreignkey-and-link-table/623956#624261) – Tilendor 2009-07-01 20:16:09