Foo
has_many Bar
. I want to do something like:
foo_instance.bars.find_with_custom_stuff(baz)
How do I define find_with_custom_stuff
so that it's available on the bars
relation? (and not just a Bar
class method?)
update
I want to do something more complicated than a scope. something like:
def find_with_custom_stuff(thing)
if relation.find_by_pineapple(thing)
relation.find_by_pineapple(thing).monkey
else
:banana
end
end
Scopes, scope
in rails 3 and named_scope
in rails 2.
class Bar
scope :custom_find, lambda {|baz| where(:whatever => baz) }
end
foo_instance.bars.custom_find(baz)
scope
should return a scope, so given your update you probably don't want to use scope
here. You can write a class method though, and use scoped
to access the current scope, like:
class Bar
def self.custom_find(thing)
if bar = scoped.find_by_pineapple(thing)
bar.monkey
else
:banana
end
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With