繁体   English   中英

如何使用Active Record范围合并条件,Rails 4

[英]How to concatonate conditions with Active Record scope, Rails 4

我正在尝试使用rails 4为Active Record模型创建一个范围。该范围涉及2个可以单独执行的条件:

1) includes(:categories).for_category("proposal") 2) where(:is_published => true)

我需要一个返回满足任一条件(不一定同时满足两个条件)的所有记录的范围。 所以像这样:

scope :proposal, -> { includes(:categories).for_category("proposal") || where(:is_published => true)}

谢谢你的帮助。

**编辑**

这里的每条评论是来自https://github.com/comfy/comfortable-mexican-sofa/blob/b16bb14bec7bffee61949d72a5f2c9eca3c95bf8/lib/comfortable_mexican_sofa/extensions/is_categorized.rb的for_category范围的定义

scope :for_category, lambda { |*categories|
  if (categories = [categories].flatten.compact).present?
    self.distinct.
      joins(:categorizations => :category).
      where('comfy_cms_categories.label' => categories)
  end
}

您需要定义一个新范围,其中包括一个SQL“ OR”。 我不知道您的“ for_category”范围在做什么,但是让我们说这有点像

scope :for_category, ->(category_name) { where("categories.name" => category_name)}

然后,您可以像这样创建一个新的作用域:请注意, where参数是值的列表,而不是哈希(哈希形式只能为与AND =测试生成sql)

scope :published_or_for_category ->(category_name){ includes(:categories).where("categories.name = ? OR proposals.is_published = ?", category_name, true) }

根据Max的建议,我可以进行以下工作:

scope :published_or_for_category, ->(category_name){
  includes(:categories).where(
  "comfy_cms_categories.label = ? OR is_published = ?",
  category_name, true
  )
}

我可能会提到以下内容似乎也适用:

scope :proposal, -> { includes(:categories).for_category("proposal") | where(:is_published => true) }

一个比另一个更好吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM