Rails-4中使用join连接2个表时无法获取所有列

3
这是我的model.rb文件。
class Compute
belongs_to :user
end

class User
has_many :computes
end

我使用此查询获取所有详细信息。
User.joins(:computes).where.not(skey: 'NULL')

我已经从USER表中获取了所有内容,同时我需要从COMPUTE表中获取一个或多个列与USER相关联。


User.where.not(skey: 'NULL').joins(:computes).collect{|usr| usr.computes.map{|po|po.attributes.merge(usr.attributes)}}..... 这是正确的解决方案吗?有没有更简单的方法? - user3437778
1
在使用连接时,您必须提及要选择的列名。例如:User.joins(:computes).where.not(skey: 'NULL').select("users.name, computes.name") - jbmyid
请使用 include 替代。User.includes(:computes).where.not(skey: 'NULL') - Pavan
你应该在查询中添加 SELECT 语句。 - Kushal
2个回答

1
你可以这样使用。
User.joins(:computes).where.not(skey: 'NULL').select("users.id, computes.name")

1

使用 .pluck 代替 .select。例如:

Table_1.joins(:table_2).where(:conditions).pluck('table_1.col_1', 'table_1.col_2', 'table_2.col_1', 'table_2.col_2')

User.joins(:computes).where.not(skey: 'NULL').pluck('users.id', 'computes.name')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接