首页 > 解决方案 > 使用涉及使用 ActiveRecord 连接表的 where 子句选择模型

问题描述

项目 == has_many ==> project_stages <== has_many == 阶段

我正在尝试选择那些 stage.name = 'completed' 的项目,所以我认为以下方法之一会起作用:

Project.joins(:stages).where(stages: { name: 'completed' })
Project.where(stage: Stage.find_by(name: 'completed'))

没有骰子。


楷模:

class Project < ApplicationRecord
  ...
  has_many :project_stages
  has_many :stages, through: :project_stages
  ...
end
class ProjectStage < ApplicationRecord
  belongs_to :project
  belongs_to :stage
end
class Stage < ApplicationRecord
  has_many :project_stages
end

标签: ruby-on-railsactiverecordwhere-clause

解决方案


我认为scopes很适合这个:

scope :search_by_stages, ->(param){
    joins(:stages).where(Stage.arel_table[:name].lower.eq(param.downcase))
  }

您可以在模型中添加scope上面定义的名称(搜索不区分大小写,如果需要区分大小写,可以删除和)。Projectparamlowerdowncase

您可以像这样使用它(如果您不熟悉范围):Project.search_by_stages('name')

希望以上对您有所帮助!


推荐阅读