Sql 如何将条件与活动记录范围联系起来,Rails 4

Sql 如何将条件与活动记录范围联系起来,Rails 4,sql,ruby-on-rails,activerecord,ruby-on-rails-4,Sql,Ruby On Rails,Activerecord,Ruby On Rails 4,我正在尝试使用rails 4为活动记录模型创建一个作用域。该范围涉及我能够单独执行的两个条件: 1) 包括(:类别)。对于_类别(“提案”) 2) where(:is_published=>true) 我需要一个范围,返回满足任一条件(不一定两者都满足)的所有记录。比如: scope :proposal, -> { includes(:categories).for_category("proposal") || where(:is_published => true)} 谢谢你的

我正在尝试使用rails 4为活动记录模型创建一个作用域。该范围涉及我能够单独执行的两个条件:

1)
包括(:类别)。对于_类别(“提案”)
2)
where(:is_published=>true)

我需要一个范围,返回满足任一条件(不一定两者都满足)的所有记录。比如:

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

**编辑**

此处的每条注释是for_类别范围的定义,取自


您需要定义一个包含sql“或”的新范围。我不知道你的“for_类别”范围在做什么,但假设它是这样的

scope :for_category, ->(category_name) { where("categories.name" => category_name)}
然后您可以创建这样一个新的作用域:请注意,
其中的
参数是一个值列表,而不是散列(散列表单只能为与
结合的
=
测试生成sql)


根据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) }

一个比另一个好吗?

什么是“for_category”范围的定义?谢谢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) }