开发者

Friendship association problem

I'm building a social network, and I'm stucked in the friendship relation. These are my data:

Table friendship:

 create_table "friendships", :force => true do |t|
t.integer  "user_id"
t.integer  "friend_id"
t.boolean  "confirmed"
t.datetime "created_at"
t.datetime "updated_at"

Association in friendship model:

   class Friendship < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, :class_name => "User"

My mistaken Association in user model:

  has_many :friendships #table that contains the reference of friends
  has_many :friends, :through=>:friendships, :conditions => ['confirmed = false'] #my performed request to others friends
  has_many :inverse_friendship, :class_name=>"Friendship", :foreign_key=>"friend_id" #someone requested friendship to me
  has_many :inverse_friends, :through=>:inverse_friendship, :source=>:user

The boolean confirmed in the table friendship, mean if the requests are accepted by both friends, it's false for default when a friend request is submitted. What I want to obtain in the model User is:

  1. has many :requests_sent # when the confirm in the Friendship model is set to false and I'm the source (user_id)

  2. has many :request_recieved # when the confirm in the Friendship model is set to false and I'm the target (friend_id)

  3. has many :frien开发者_运维技巧ds #when the confirm in the Friendship model is set to true and I'm either the source (user_id) or the target (friend_id)

    As you can notice from the code I posted I tried to put :condition=>'confirmed=false', but rails apply the condition to the user model, not to the Friendship model, so that's not the right way to achieve my 3 goals, with a free method in the model User ? Tnx

P.S I don't want change my models, I just would like to have a solution for the existing ones


An option would be to put the condition in the friendship model as a named_scope, then you should be able to do something like:

@user.friends.confirmed

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜