Ruby on rails rails使用includes进行选择

Ruby on rails rails使用includes进行选择,ruby-on-rails,activerecord,rails-postgresql,Ruby On Rails,Activerecord,Rails Postgresql,我的rails 3.2应用程序中有这些代码 User.includes(:profile).limit(10) 从profiles表中选择所有字段我需要一种从profiles表中选择特定字段的方法来减少数据库查询 我在用postgresql我想你,问一下方法 更新: 来自@Hassan的答案根本不起作用。外观(快速加载部分) 由于一次只加载一个表,因此条件或订单不能引用主表以外的表 请尝试以下操作: class User < ActiveRecord::Base has_one :p

我的rails 3.2应用程序中有这些代码

User.includes(:profile).limit(10)
从profiles表中选择所有字段我需要一种从profiles表中选择特定字段的方法来减少数据库查询 我在用postgresql

我想你,问一下方法

更新:

来自@Hassan的答案根本不起作用。外观(快速加载部分)

由于一次只加载一个表,因此条件或订单不能引用主表以外的表

请尝试以下操作:

class User < ActiveRecord::Base
  has_one :profile_w_name, -> { select(:id, :name, :user_id).limit(10) }, class_name: 'Profile'
end

User.includes(:profile_w_name).first.profile_w_name

另外,请查看此要点以了解不同之处

您最好使用以下内容

User.joins(:profile).select("users.*, profiles.field1, profiles.field2").limit(10)

Rails 5路:只需添加对关联表名的引用

User.includes(:profile).select("users.*, profiles.field1, profiles.field2").limit(10).references(:profiles)

它将从用户表中选择我想从配置文件表中选择特定字段为什么你这么认为?你试过要点了吗?如果我理解并纠正了第二次更新,你可以这样做吗
@users=User.includes(:profile)。选择('User.id,User.name,profile.id,profile.something,profile.something_else')。引用(:profile)
?这样会生成两个类似的查询吗
SELECT id,name FROM users
SELECT id,something,something FROM profiles WHERE user_id IN(此处为userid)
@Lykos,我在gist中为您留下了一条带有调试输出的注释。可能与Try now重复。我在拨打limit(10)时漏掉了“.”接线员。现在修好了,但还是不行。你可以检查这个答案
User.joins(:profile).select("users.*, profiles.field1, profiles.field2").limit(10)
User.includes(:profile).select("users.*, profiles.field1, profiles.field2").limit(10).references(:profiles)