2

私はクライアント用にRailsプロジェクトを設定していますが、ユーザー(モデル)が(Twitterのように)お互いをフォローできるようにしたいと考えています。また、あるユーザーが別のユーザーをフォローし始めた時期を追跡できるようにしたいとも考えています。

作成日を追跡する必要があるので、has_many X, :through => Y関係が進むべき道であると考えました。したがって、Yは作成日を追跡します。

フォローモデルを設定しました:

class Follow < ActiveRecord::Base
  attr_accessible :actor_id, :observer_id, :follower, :followee
  attr_readonly :actor_id, :observer_id, :follower, :followee

  belongs_to :follower, :class_name => 'User', :foreign_key => :observer_id
  belongs_to :followee, :class_name => 'User', :foreign_key => :actor_id

  validates_presence_of :follower, :followee
  validates_uniqueness_of :actor_id, :scope => :observer_id
end

問題は、ユーザーモデルでリレーションを設定するにはどうすればよいですか?

理想的には、次のものが必要です。

  • :follows関連付けられたFollowオブジェクトになります。selfはfollower(observer_id)です。
  • :followed関連付けられたFollowオブジェクトになります。selfはfollowee(actor_id)です。
  • :following関連付けられたUserオブジェクトであり、selfはフォロワー(observer_id)です。
  • :followers関連付けられたUserオブジェクトであり、selfはfollowee(actor_id)です。

has_many :throughパーツの書き方がわかりませんが?またはを使用する必要があります:source => Xforeign_key => X?そして、どのキー(actor_idまたはobserver_id)をそれぞれに入れる必要がありますか?

編集:私は現在これを行っています

has_many :follows, :foreign_key => :observer_id
has_many :followed, :class_name => 'Follow', :foreign_key => :actor_id
has_many :following, :class_name => 'User', :through => :follows, :source => :followee, :uniq => true
has_many :followers, :class_name => 'User', :through => :follows, :source => :follower, :uniq => true

そしてそれはほとんど機能しています。それらのすべては:followers正常に動作しますが、user.followers何か奇妙なことをしています。ユーザーが誰かをフォローしているかどうかをチェックしているuser.followersようです。フォローしている場合は、ユーザーのみを含む配列を返します。そうでない場合は、空の配列を返します。

誰かアドバイスはありますか?

4

1 に答える 1

0

It looks like this is the correct format:

has_many :follows, :foreign_key => :observer_id
has_many :followed, :class_name => 'Follow', :foreign_key => :actor_id
has_many :following, :class_name => 'User', :through => :follows, :source => :followee, :uniq => true
has_many :followers, :class_name => 'User', :through => :followed, :source => :follower, :uniq => true

For Rails newbies, the :uniq => true is important (as I discovered while doing this) because it keeps has_many X, :through => Y relations from returning duplicates (that is, without it, you might get multiple distinct objects, each with their own object ID, all referring to the same record/row).

于 2013-01-18T18:14:28.390 に答える