【问题标题】:rails scope using "AND"使用“AND”的轨道范围
【发布时间】:2018-01-06 21:10:54
【问题描述】:

我有 2 个范围,by_group_title 确实用于搜索框中,以根据用户搜索返回组名。它工作得很好,但是,我试图限制可以在搜索结果中返回哪些组。具体来说,我试图排除任何“成员资格”为“受限”的组,我只希望当组的“成员资格”设置为“标准”时,搜索结果中返回的组。

我拥有的第二个范围称为 by_standard_membership。此范围将返回标准组,但不允许搜索。所以我试图找到一种方法来结合这两个范围,以便用户可以搜索组标题,但只显示标准组,而受限组不会出现在搜索结果中。

我一直在尝试使用“and”语句来组合它们,但似乎无法让它发挥作用。

#scopes
scope :by_group_title, -> (group) { where('title LIKE ?',"%#{group}%" ).order(created_at: :desc) if group.present? }
scope :by_standard_membership, -> { where(membership: "Standard").order(created_at: :desc) }

【问题讨论】:

  • 如果将两个where 子句链接为.where().where(),它们将通过AND 连接。这有帮助吗?
  • 感谢成功,没有意识到你可以将 .where() 链接到另一个 .where() 效果很好。

标签: ruby-on-rails ruby-on-rails-5


【解决方案1】:

有几种方法可以做到这一点。在下面的示例中,我已将条件(AND)someNum = 1 添加到您提供的表达式中。

您可以将AND 添加到where 子句...

scope :by_group_title, -> (group) { where('title LIKE ? and someNum = 1',"%#{group}%" ).order(created_at: :desc) if group.present? }

或者使用 ActiveRecord 字段...

scope :by_standard_membership, -> { where(membership: "Standard", someNum: 1).order(created_at: :desc) }

或者,您可以将where 子句链接在一起...

scope :by_standard_membership, -> { where(membership: "Standard").where(someNum: 1).order(created_at: :desc) }

【讨论】:

  • 感谢您的回答。我最终链接了 where 子句。 scope :by_group_title, -> (group) { where('title LIKE ?',"%#{group}%" ).where(membership: "Standard").order(created_at: :desc) if group.present? }
猜你喜欢
  • 1970-01-01
  • 2014-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 2012-08-03
相关资源
最近更新 更多