delisdeli delisdeli - 5 months ago 19
SQL Question

Friendship has_many through model with multiple status'

Currently my User model has the following code:

has_many :notifications
has_many :friendships
has_many :friends, :through => :friendships, :conditions => { status: 'accepted' }
has_many :requested_friends, :through => :friendships, :source => :friend, :conditions => { status: 'requested' }
has_many :pending_friends, :through => :friendships, :source => :friend, :conditions => { status: 'pending' }


And my Friendship model is as follows:

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

def self.request(user, friend)
unless user == friend or Friendship.exists?(user_id: user, friend_id: friend)
transaction do
Friendship.create(:user => user, :friend => friend, :status => 'pending')
Friendship.create(:user => friend, :friend => user, :status => 'requested')
end
else
return "failed"
end
end

def self.accept(user, friend)
unless user == friend or Friendship.exists?(user_id: user, friend_id: friend)
transaction do
accepted_at = Time.now
accept_one_side(user, friend, accepted_at)
accept_one_side(friend, user, accepted_at)
end
else
return "failed"
end
end

def self.accept_one_side(user, friend, accepted_at)
request = find_by_user_id_and_friend_id(user, friend)
request.status = 'accepted'
request.accepted_at = accepted_at
request.save!
end


When I try to run my cucumber tests, however, I am getting this error:

SQLite3::SQLException: no such column: users.status: SELECT "users".* FROM "users" INNER JOIN "friendships" ON "users"."id" = "friendships"."friend_id" WHERE "users"."status" = 'accepted' AND "friendships"."user_id" = ? (ActionView::Template::Error)


I think that this means it is trying to only include inside in for example pending_friends, users which have the attribute status = "pending", where it should actually be including users who belong to friendships which have attribute status = "pending"

Is this right? How would I go about fixing this?

Answer

I have updated to the following and this works:

  has_many :notifications
  has_many :friendships
  has_many :accepted_friendships, :class_name => "Friendship", :conditions => {status: 'accepted'}
  has_many :requested_friendships, :class_name => "Friendship", :conditions => {status: 'requested'}
  has_many :pending_friendships, :class_name => "Friendship", :conditions => {status: 'pending'}
  has_many :friends, :through => :accepted_friendships
  has_many :requested_friends, :through => :requested_friendships, :source => :friend
  has_many :pending_friends, :through => :pending_friendships, :source => :friend

If anyone has a different approach without having to create accepted_friendshis, requested_friendships, and pending_friendships, however, I would love to hear it!