项目== 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
我认为scopes
非常适合这个:
scope :search_by_stages, ->(param){
joins(:stages).where(Stage.arel_table[:name].lower.eq(param.downcase))
}
您可以在Project
模型中添加上面定义的scope
,其中param
是名称(该搜索不区分大小写,如果需要区分大小写的话,您可以删除lower
和downcase
(。
您可以这样使用它(以防您不熟悉范围(:Project.search_by_stages('name')
希望以上能有所帮助!👍