[英]How to concatonate conditions with Active Record scope, Rails 4
I am trying to create a scope for an Active Record model using rails 4. The scope deals with 2 conditions which I am able to execute individually: 我正在尝试使用rails 4为Active Record模型创建一个范围。该范围涉及2个可以单独执行的条件:
1) includes(:categories).for_category("proposal")
2) where(:is_published => true)
1) includes(:categories).for_category("proposal")
2) where(:is_published => true)
I need a scope that returns all records where either condition is met (not necessarily both). 我需要一个返回满足任一条件(不一定同时满足两个条件)的所有记录的范围。 So something like: 所以像这样:
scope :proposal, -> { includes(:categories).for_category("proposal") || where(:is_published => true)}
Thanks for any help. 谢谢你的帮助。
**EDIT** **编辑**
Per comment here is the definition of the for_category scope taken from https://github.com/comfy/comfortable-mexican-sofa/blob/b16bb14bec7bffee61949d72a5f2c9eca3c95bf8/lib/comfortable_mexican_sofa/extensions/is_categorized.rb 这里的每条评论是来自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
}
You'll need to define a new scope which includes an sql "OR". 您需要定义一个新范围,其中包括一个SQL“ OR”。 I don't know what your "for_category" scope is doing but let's say it's something like 我不知道您的“ for_category”范围在做什么,但是让我们说这有点像
scope :for_category, ->(category_name) { where("categories.name" => category_name)}
Then you could make a new scope like this: note that the where
arguments are a list of values rather than a hash (the hash form can only produce sql for =
tests joined with AND
) 然后,您可以像这样创建一个新的作用域:请注意, where
参数是值的列表,而不是哈希(哈希形式只能为与AND
=
测试生成sql)
scope :published_or_for_category ->(category_name){ includes(:categories).where("categories.name = ? OR proposals.is_published = ?", category_name, true) }
Based on Max's suggestions I got the following to work: 根据Max的建议,我可以进行以下工作:
scope :published_or_for_category, ->(category_name){
includes(:categories).where(
"comfy_cms_categories.label = ? OR is_published = ?",
category_name, true
)
}
I might mention that the following seems to work as well: 我可能会提到以下内容似乎也适用:
scope :proposal, -> { includes(:categories).for_category("proposal") | where(:is_published => true) }
Is one better that the other? 一个比另一个更好吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.