Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a custom finder method on an ActiveRecord relation?

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
like image 577
John Bachir Avatar asked Aug 13 '11 21:08

John Bachir


1 Answers

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
like image 119
numbers1311407 Avatar answered Nov 01 '22 06:11

numbers1311407