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

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
A40f08a2dfcbf7feab0c9bc063c01f9c?d=identicon&s=25 pankaj (Guest)
on 2009-02-20 13:39
(Received via mailing list)
class User

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


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"
end

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,
Regards,
Pankaj
561ded75345e3657835b48269a51bb2f?d=identicon&s=25 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.
8853f712852b03ba6646b59b1723f44d?d=identicon&s=25 Flower Born (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
this:

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

However, you can't do sth. like

  @user.pending_friends << @friend

anymore in this way. See:

http://rails.lighthouseapp.com/projects/8994/ticke...

Jan

* pankaj <pankajbhageria@gmail.com> [2009-02-20 04:30:09 -0800]:
561ded75345e3657835b48269a51bb2f?d=identicon&s=25 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:

https://gist.github.com/82c50486bc38b7d7c880

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

Cheers
Luke
This topic is locked and can not be replied to.