This project is archived and is in readonly mode.
add has_element? method to models with has_many/through associations
Reported by Josh Susser | April 25th, 2008 @ 11:57 PM
When using a model that is associated (via has_many) with other models, it is often convenient to be able to ask the containing model whether it contains (or "has") a specific item. This patch adds such a method to the containing class. So, for example, if
User.has_many :friends
alex.has_friend?(josh)
will return true if josh is a friend of alex.
Works for both has_many and has_many_through associations.
Written (as a monkey patch) by Nick Kallen, patched by Josh Susser and Alex Chaffee.
Comments and changes to this ticket
-
duncanbeevers April 29th, 2008 @ 08:01 PM
Instead of invoking find_by_id and instantiating a new model, could you instead rely on the optimized include? association method?
-
DHH April 29th, 2008 @ 10:27 PM
I don't think I understand the difference between alex.friends.include?(josh) and alex.has_friend?(josh)? (now that the include? call has been optimized to not load the whole collection).
-
Josh Susser April 29th, 2008 @ 11:13 PM
David, this was an extract of something we wrote before include? got that optimization, so yes, it's equivalent functionality now. If you care about Law of Demeter, this little bit of magic lets you avoid chaining off the association. Maybe it's just fluff now. I guess it's all a question of which API you like better.
-
DHH April 29th, 2008 @ 11:18 PM
- State changed from new to resolved
Ah, okay. Yeah, I could definitely see this make sense before the include? fix. I don't think we need it now, though.
Create your profile
Help contribute to this project by taking a few moments to create your personal profile. Create your profile »
<h2 style="font-size: 14px">Tickets have moved to Github</h2>
The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>
People watching this ticket
Attachments
Tags
Referenced by
- 2425 [PATCH] Add methods on active record to denote whether any associated objects exist for that association note that #49 was similar and denied - although this has ...
- 4865 [Feature Request] add :if / :unless conditions for attr_accessible, attr_protected and attr_readonly Discussion at state_machine lighthouse: http://pluginawe...