3

ここで自己参照関係に関する Railscast を見てきました: http://railscasts.com/episodes/163-self-referential-association

これに基づいて、友情に「ステータス」フィールドを含めて、友情を要求して受け入れる必要があるようにしました。「ステータス」はブール値です。まだ応答がない場合は false、承認された場合は true です。

私の問題は、現在のユーザー (私は Devise を使用しています) と別のユーザーを指定して、フレンドシップ オブジェクトを見つける方法を考え出すことです。

これが私が利用できるものです:

current_user.friends              # lists people you have friended
current_user.inverse_friends      # lists people who have friended you
current_user.friendships          # lists friendships you've created
current_user.inverse_friendships  # lists friendships someone else has created with you
friendship.friend                 # returns friend in a friendship

友情のステータスを簡単に確認できるように、次のような方法を探しています。

current_user.friendships.with(user2).status

ここに私のコードがあります: 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

友情.rb

belongs_to :user
belongs_to :friend, :class_name => "User"

私がそれをしている間-ユーザーの友達を表示するには、「current_user.friends」「current_user.inverse_friends 」の両方を表示する必要があります-「current_user.friends を呼び出して、それをそのままにする方法はありますか2つの結合?

4

1 に答える 1

0

次のようにして、特定の関連付けに条件を渡すことができます。

has_many :friends, :class_name => 'User', :conditions => 'accepted IS TRUE AND (user = #{self.send(:id)} || friend = #{self.send(:id)})"'

注: send を使用しているため、属性を取得しようとするまで属性を評価しません。

「.with(user2)」構文が本当に必要な場合は、named_scope などを介して実行できる可能性があります。

Class Friendship
  named_scope :with, lambda { |user_id|
      { :conditions => { :accepted => true, :friend_id => user_id } }
    }
end

許可する必要があります:

user1.friendships.with(user2.id)

注: コードはテストされていません - バグ修正が必要な場合があります...

于 2011-07-18T17:47:35.473 に答える