Rails子查询始终返回nil值

时间:2015-10-22 14:02:56

标签: ruby-on-rails ruby postgresql

我需要在subselect中计算其他表中的行,所以我使用这个查询:

follows_sql = Follow.where(followable_type: 'Idea').where('follows.followable_id = ideas.id').select('COUNT(followable_id)').to_sql

idea = Idea.select("(#{follows_sql}) AS fcnt").includes(:collaborations).
  where(collaborations: { user_id: 4, owner: true })

所以它产生了有效的SQL,但我无法访问' fcnt'来自idea var的价值。我尝试用不同的方式做到:

idea[0].fcnt   # return nil
idea[0]["fcnt"]  # return nil

但我只能访问Idea模型中存在的字段。 我如何访问我的自定义' fcnt '领域? enter image description here

1 个答案:

答案 0 :(得分:1)

我认为以下内容应该对你有用

idea = Idea.select("ideas.*, COUNT(follows.id) AS fcnt").joins("LEFT OUTER JOIN follows ON follows.followable_id = ideas.id").group("ideas.id")

ideas.each do |idea|
  puts idea.fcnt
  # Should output a number
end

请注意,我遗漏了其他包含和where子句。首先尝试解决问题,如果此查询有效,请添加其他子句。

另外,如果您正确设置了关系,这样一个想法会有很多,那么您可以通过执行类似

的操作来清理代码
ideas = Idea.includes(:collaborations).where(collaborations: { user_id: 4, owner: true })

ideas.map { |idea| idea.follows.count }
相关问题