在ActiveRecord关系上定义自定义查找程序方法?

Joh*_*hir 5 ruby activerecord ruby-on-rails

Foohas_many Bar.我想做的事情如下:

foo_instance.bars.find_with_custom_stuff(baz)
Run Code Online (Sandbox Code Playgroud)

如何定义find_with_custom_stuff以便在bars关系中可用?(而不只是一个Bar类方法?)

更新

我想做一些比范围更复杂的事情.就像是:

def find_with_custom_stuff(thing)
  if relation.find_by_pineapple(thing)
    relation.find_by_pineapple(thing).monkey
  else
    :banana
  end
end
Run Code Online (Sandbox Code Playgroud)

num*_*407 5

范围,scope在轨道3和named_scope在轨2.

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

foo_instance.bars.custom_find(baz)
Run Code Online (Sandbox Code Playgroud)

scope应该返回一个范围,所以鉴于你的更新,你可能不想在scope这里使用.您可以编写一个类方法,并用于scoped访问当前范围,如:

class Bar
  def self.custom_find(thing)
    if bar = scoped.find_by_pineapple(thing)
      bar.monkey
    else
      :banana
    end
  end
end
Run Code Online (Sandbox Code Playgroud)