Thomas Counsell
2005-Jan-06 20:06 UTC
Request: in_association? method for has_and_belongs_to_many?
Hello I have a request for the next version of rails. Could we have an in_association?( other_object) for has_and_belongs_to_many associations. I seem to have need for it quite a lot, for instance when I have a User object which :has_and_belongs_to_many Group objects. I wish to check whether a User is in a particular Group. User has_and_belongs_to_many :groups def in_group?( group_to_check ) groups.find( group_to_check.id ) rescue ActiveRecord::RecordNotFound false end end Would be nice to have the template do it automatically. Unfortunately, I can''t quite figure out from the code where these automatic methods are created? If anyone can point me in the right direction I''ll happily create a patch. Thanks Tom PS Why does HasAndBelongsToMany.find raise an error if it doesn''t find anything, and not just return nil or an empty array? I prefer errors to only take place when something unexpected takes place, rather than expected results....
Marcel Molina Jr.
2005-Jan-08 21:12 UTC
Re: Request: in_association? method for has_and_belongs_to_many?
On Thu, Jan 06, 2005 at 08:06:24PM +0000, Thomas Counsell wrote:> I have a request for the next version of rails. Could we have an > in_association?( other_object) for has_and_belongs_to_many > associations. > > I seem to have need for it quite a lot, for instance when I have a User > object which :has_and_belongs_to_many Group objects. I wish to check > whether a User is in a particular Group. > > User > has_and_belongs_to_many :groups > > def in_group?( group_to_check ) > groups.find( group_to_check.id ) > rescue ActiveRecord::RecordNotFound > false > end > end > > Would be nice to have the template do it automatically. Unfortunately,The record''s associations are simply an array of AR objects so you can use Array#include? e.g. some_user.groups.include? some_group hope this helps, marcel -- Marcel Molina Jr. <marcel-WRrfy3IlpWYdnm+yROfE0A@public.gmane.org>
evan
2005-Jan-08 23:16 UTC
Re: Request: in_association? method for has_and_belongs_to_many?
> > def in_group?( group_to_check ) > > groups.find( group_to_check.id ) > > rescue ActiveRecord::RecordNotFound > > false > > end > > end > > > > Would be nice to have the template do it automatically. Unfortunately, > > The record''s associations are simply an array of AR objects so you can > use Array#include? > > e.g. > > some_user.groups.include? some_group >Although we could use include, it''d be clearer from the template designer''s perspective to use in_group? Of course, it''s not hard to add that in a base model which you add that method :-) Ah the glory of ruby. -rabble