Define a custom search method with respect to ActiveRecord?

Foohas_many Bar. I want to do something like:

foo_instance.bars.find_with_custom_stuff(baz)

How to determine find_with_custom_stuffthat it is available in relation bars? (and not just a class method Bar?)

Update

I want to do something more complex than an area. sort of:

def find_with_custom_stuff(thing)
  if relation.find_by_pineapple(thing)
    relation.find_by_pineapple(thing).monkey
  else
    :banana
  end
end
+5
source share
1 answer

Areas scopein rails 3 and named_scopein rails 2.

class Bar
  scope :custom_find, lambda {|baz| where(:whatever => baz) }
end

foo_instance.bars.custom_find(baz)

scopeshould return an area, so given your update, you probably don't want to use scopehere. However, you can write a class method and use it scopedto access the current scope, for example:

class Bar
  def self.custom_find(thing)
    if bar = scoped.find_by_pineapple(thing)
      bar.monkey
    else
      :banana
    end
  end
end
+5

All Articles