【发布时间】:2015-10-23 00:35:01
【问题描述】:
我需要在子选择中计算其他表的行数,所以我使用这个查询:
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,但我无法从 idea var 访问 'fcnt' 值。我尝试以不同的方式做到这一点,例如:
idea[0].fcnt # return nil
idea[0]["fcnt"] # return nil
【问题讨论】:
-
idea[0].attributes说什么? -
所有idea的属性列表,存在于数据库中
-
attributes模型上的哈希包含对应结果集每一行的所有获取的字段。显然,选择在某个时候失败了。嗯…… -
查看我的更新屏幕,您会看到 SQL 看起来不错
-
嗯..也许您描述了您的表以及您要查询的内容?
标签: ruby-on-rails ruby postgresql