Forum: Ruby on Rails Altering the accessor of an association collection

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.
Jon L. (Guest)
on 2006-01-02 14:24
I want to be able to do something like this (for example):

class Person < ActiveRecord::Base
  has_many :friends

  def friends(living_in = :uk)
    # filter based on parameters here
  end
end

Is there any way I can redefine the accessor for an association whilst
still being able to get the values? Basically, I'm looking for an
equivilent of read_attribute() for associations.
Jon L. (Guest)
on 2006-01-02 14:45
Actually don't worry about this, I changed my code so I don't need it.
Jarkko L. (Guest)
on 2006-01-02 14:46
(Received via mailing list)
On 2.1.2006, at 14.24, Jon L. wrote:

> I want to be able to do something like this (for example):
>
> class Person < ActiveRecord::Base
>   has_many :friends
>
>   def friends(living_in = :uk)
>     # filter based on parameters here
>   end

You can use the automatic Active Record methods for this, too:

jake = Person.find :first
jake.friends.find_all_by_living_in("uk")

If you think it's worth it, you can also write your own friends
method. I can't really see a reason for that, though. Maybe I
misunderstood something.

//jarkko
Jon L. (Guest)
on 2006-01-02 18:43
Jarkko L. wrote:
> On 2.1.2006, at 14.24, Jon L. wrote:
>
>> I want to be able to do something like this (for example):
>>
>> class Person < ActiveRecord::Base
>>   has_many :friends
>>
>>   def friends(living_in = :uk)
>>     # filter based on parameters here
>>   end
>
> You can use the automatic Active Record methods for this, too:
>
> jake = Person.find :first
> jake.friends.find_all_by_living_in("uk")
>
> If you think it's worth it, you can also write your own friends
> method. I can't really see a reason for that, though. Maybe I
> misunderstood something.

Perhaps my example wasn't the best -- it's actually just a simplified
example of something I'm doing which isn't anything to do with People or
Friends.

Basically I have a recursive object which makes up a tree of nodes --
imagine friends being of class Person as well (so I guess it would have
been better to say "has_many :people" or something). Sometimes I would
want friends and its all descendants; sometimes I just want friends; and
sometimes I want friends, and descendants, excluding where a boolean
attribute is true.

Anyway, thanks for the info; I hadn't thought of calling finders on a
collection like that, but I've found an adaquate way to solve the
problem.

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