加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 在ActiveRecord关系上定义自定义查找程序方法

发布时间:2020-12-17 03:13:15 所属栏目:百科 来源:网络整理
导读:Foo has_many Bar.我想做的事情如下: foo_instance.bars.find_with_custom_stuff(baz) 如何定义find_with_custom_stuff以使其在条形关系中可用? (而不仅仅是一个Bar类方法?) 更新 我想做一些比范围更复杂的事情.就像是: def find_with_custom_stuff(thin
Foo has_many Bar.我想做的事情如下:

foo_instance.bars.find_with_custom_stuff(baz)

如何定义find_with_custom_stuff以使其在条形关系中可用? (而不仅仅是一个Bar类方法?)

更新

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

def find_with_custom_stuff(thing)
  if relation.find_by_pineapple(thing)
    relation.find_by_pineapple(thing).monkey
  else
    :banana
  end
end

解决方法

轨道3中的范围,范围和轨道2中的named_scope.

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

foo_instance.bars.custom_find(baz)

范围应返回范围,因此在给定更新时,您可能不希望在此处使用范围.您可以编写类方法,并使用作用域来访问当前范围,如:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读