编写命名范围的更好方法?

发布于 2024-11-18 12:17:23 字数 500 浏览 0 评论 0原文

这个命名范围工作正常。

named_scope :search, lambda {|search_txt|
      {
        :conditions => ["field1 like ? or field2 like ? or field3 like ?","#{search_txt}%","#{search_txt}%","#{search_txt}%"]
      }
  }

而不是在条件中写三次search_txt。我可以通过在条件中仅传递一次 search_txt 来处理相同的场景吗?

named_scope :search, lambda {|search_txt|
      {
        :conditions => ["field1 like ? or field2 like ? or field3 like ?","#{search_txt}%"]
      }

}

This named scope is working fine.

named_scope :search, lambda {|search_txt|
      {
        :conditions => ["field1 like ? or field2 like ? or field3 like ?","#{search_txt}%","#{search_txt}%","#{search_txt}%"]
      }
  }

Instead of writing search_txt three time in conditions. Can I handle the same scenario with passing search_txt only once in conditions ?

Something like

named_scope :search, lambda {|search_txt|
      {
        :conditions => ["field1 like ? or field2 like ? or field3 like ?","#{search_txt}%"]
      }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

妄断弥空 2024-11-25 12:17:23

我不知道这是否适用于某个范围,但还有另一种编写条件的方法:

MyModel.all(:conditions=>['field_1 LIKE :q OR field_2 LIKE :q OR field_3 LIKE :q', {:q=> 'search_txt'}])

I don't know if this works in a scope, but there is another way to write conditions:

MyModel.all(:conditions=>['field_1 LIKE :q OR field_2 LIKE :q OR field_3 LIKE :q', {:q=> 'search_txt'}])
北方的韩爷 2024-11-25 12:17:23

这应该有效:

named_scope :search, lambda {|search_txt|
  {
    :conditions => ["field1 like :q or field2 like :q or field3 like :q",{:q => "#{search_txt}%"}]
  }

}

This should work:

named_scope :search, lambda {|search_txt|
  {
    :conditions => ["field1 like :q or field2 like :q or field3 like :q",{:q => "#{search_txt}%"}]
  }

}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文