ruby-on-rails - 使用涉及使用 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
解决方案
我认为scopes
很适合这个:
scope :search_by_stages, ->(param){
joins(:stages).where(Stage.arel_table[:name].lower.eq(param.downcase))
}
您可以在模型中添加scope
上面定义的名称(搜索不区分大小写,如果需要区分大小写,可以删除和)。Project
param
lower
downcase
您可以像这样使用它(如果您不熟悉范围):Project.search_by_stages('name')
希望以上对您有所帮助!
推荐阅读
- java - Spring config 创建假 bean 以满足测试的依赖关系
- django - django 参考用户模型 - 您正在尝试在没有默认值的情况下向问题添加不可为空的字段“作者”
- javascript - 在对话框材质 UI 中使用幻灯片转换时,React Tour 的位置错误
- rabbitmq - 使用 SSL 连接时出现 RabbitMQ 连接问题
- python - 如何在 Python 中绘制逻辑回归的决策边界?
- selenium-webdriver - 如何使用 Web 驱动程序单击并输入文本编辑器文件。. 我尝试了各种定位器但无法正常工作
- matlab - 在多个功能块之间共享大型结构
- marklogic - JSON 文档的模式验证
- javascript - 警告:flatten 不是函数使用 --force 继续
- sql - 如何在 SQL Server 中发送带有屏蔽正则表达式的查询?