新手问题 Rails has_many 关联查询问题

return · 2018年04月02日 · 最后由 xiayuanyin 回复于 2018年04月02日 · 1500 次阅读

两张表:users、projects; 其中 projects 表的字段如下

d user_id, position, index

关联关系:

Class User < ActiveRecord::Base
   has_many:projects,  :dependent => :destroy
end

当我查询用户的 projects 时候,会有多组值

user.projects  结果如下

id  user_id  position  index
1    12          1       1
2    12          2       1
3    12          3       1
4    12          1       2
5    12          2       2
6    12          3       2

我想的结果是:能否通过一次查询只取 index 最大的一组值(比如:4、5、6 记录) 最好是在 has_many 关联的时候就设置,比如:

#  伪码如下
has_many :projects, -> {max ('index')}

希望各位大神多多关照,非常感谢!!!

方案一:

has_many :projects, -> {joins('inner joins (select user_id, max(index) max_index from  projects group by user_id) grouped_projects on grouped_projects.user_id=projects.user_id and grouped_projects.max_index=projects.index')}

当然也可以给 grouped_projects 存成一个 view,如果 projects 表数据多则会对数据库开销比较大

方案二:

给 projects 加一个字段index_max<Boolean>,然后直接加在 where 条件里;index_max 字段在数据库设置触发器自动计算或者在 rails 的 ActiveRecord 里 after_save 关联计算

需要 登录 后方可回复, 如果你还没有账号请 注册新账号