Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

add has_element? method to models with has_many/through associations

#49

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.

Reported by Josh Susser · April 25th, 2008 @ 11:57 PM

State: resolved
Milestone: none
Assigned to: nobody
Importance: none

Activity

  1. Josh Susser
    Josh Susser

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

    April 28th, 2008 @ 04:06 PM

  2. duncanbeevers
    duncanbeevers

    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...

    April 29th, 2008 @ 08:01 PM

  3. DHH
    DHH

    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).

    April 29th, 2008 @ 10:27 PM

  4. Josh Susser
    Josh Susser

    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.

    April 29th, 2008 @ 11:13 PM

  5. DHH
    DHH
    • 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.

    April 29th, 2008 @ 11:18 PM