This project is archived and is in readonly mode.

#49 ✓resolved
Josh Susser

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

  • Josh Susser

    Josh Susser April 28th, 2008 @ 04:06 PM

    Attaching new patch - previous one was missing a test case.

  • duncanbeevers

    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?

    http://dev.rubyonrails.org/chang...

  • DHH

    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

    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

    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>

Attachments

Referenced by

Pages