Forum: Ruby on Rails has many :through a named scope

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
pankaj (Guest)
on 2009-02-20 13:39
(Received via mailing list)
class User

has_many :friendships
has_many :friends, :through =>  :friendship

class Friendship
  belongs_to :user
  belongs_to :friend, :class_name => 'User'
  named_scope :accepted, :conditons => "is_accepted = true"
  named_scope :pending, :conditons => "is_accepted = false"

Here in the User class, i want to write
has_many :pending_friends, through a named scope friendships accepted
has_many:accepted_friends through a named scope pending

Please help,
Luke Redpath (Guest)
on 2009-02-20 18:09
(Received via mailing list)
I'm also trying to find a way of doing this if anybody has any
suggestions; will report back if I find a way of doing it.
523b8d210ec9dea129f921b53316dbca?d=identicon&s=25 Flower B. (flowerborn)
on 2009-02-20 18:24
(Received via mailing list)
Hi Pankaj,

I don't know how to do this with named_scope, but maybe you'll like

  class User
    has_many :pending_friends, :through => :friendship, :source =>
:friend, :conditions => {'friendships.is_accepted' => 'true'}

However, you can't do sth. like

  @user.pending_friends << @friend

anymore in this way. See:


* pankaj <> [2009-02-20 04:30:09 -0800]:
Luke Redpath (Guest)
on 2009-02-20 18:49
(Received via mailing list)
Using :conditions will work but the problem is that you've just
introduced duplication between the conditions and the named_scope.
Anyway, here's my initial pass at trying to solve this:

It only works for conditions at the moment which was enough for me;
please do fork the gist and hack away!

This topic is locked and can not be replied to.