gpt4 book ai didi

ruby-on-rails - Ruby复杂查询优雅解决方案

转载 作者:数据小太阳 更新时间:2023-10-29 08:09:09 27 4
gpt4 key购买 nike

在我的 Rails 4 项目中,我有以下表格 enter image description here

在此SO question ,我搜索了一个 SQL 查询以获取具有实际项目状态 id = XX 的项目。实际上,我指的是具有 max(created_at) 的那个。

我的查询得到了答案

select p.* from projects p
left join projects_status_projects psp on (psp.project_id = p.id)
where created_at = (select max(created_at) from projects_status_projects
where project_id = p.id)
and project_status_id = XX

我的模型已定义

class Project < ActiveRecord::Base
has_many :projects_status_projects
has_many :projects_statuses, :through => :projects_status_projects
end

class ProjectStatus < ActiveRecord::Base
has_many :projects_status_projects
has_many :projects, :through => :projects_status_projects
end

class ProjectsStatusType < ActiveRecord::Base
belongs_to :project
belongs_to :project_status
end

在我的 Project 模型中,我有以下方法

def self.with_status(status)
joins(:projects_status_projects)
.where('projects_status_projects.created_at = (select max(created_at) from
projects_status_projects where project_id = p.id)')
.where('projects_status_projects.project_status_id = ?', status)
end

虽然查询是正确的,但接收到的结果被很好地过滤了,我觉得这个解决方案很糟糕,一点也不优雅。

有什么方法可以用范围获得相同的结果吗?

感谢您的帮助。

最佳答案

你觉得怎么样

scope :with_status, -> (status) { 
ProjectsStatusType.where(:project_status_id, status).order(:created_at).last.project
}

根据评论编辑:

正如 sockmonk 所说,范围应该是可链接的。这是一种更简洁的方法,如果找不到项目,它也可以解决问题。

# ProjectStatusType model
scope :with_ordered_status, -> (status) {
where(:project_status_id, status).order(:created_at)
}

# Project model
def self.find_by_status(status)
project_statuses = ProjectsStatusType.with_ordered_status(status)
project_statuses.any? ? project_statuses.last.project : nil
end

关于ruby-on-rails - Ruby复杂查询优雅解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19251527/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com