2013-08-02 72 views
2

我有這些代碼在我的Rails 3.2的應用程序軌選擇與包括

User.includes(:profile).limit(10) 

其選擇概況表我需要一種方法來從配置表上的特定字段選擇減少數據庫的所有字段查詢我使用 postgresql

+2

的可能重複的更好 - (HTTP [Rails 3中與包含選擇?]:// stackoverflow.com/questions/4047833/rails-3-select-with-include) – Benj

回答

5

我想你,請問select方法。

User.includes(:profile).limit(10).select(:field1, :field2) 

更新:

從@Hassan答案woudn't真正發揮作用。看here(預先加載部分)

Since only one table is loaded at a time, conditions or orders cannot reference tables other than the main one.

嘗試以下操作:

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_id領域,由於AR將嘗試預加載配置文件字段。

更新:

我找到上述所有更好的解決方法,請參見後棄用抱怨預先加載和SQL片斷像select("post.id, comment.post_id")引用。需要Rails 4。

User.includes(:profile).select(:field1, :field2).references(:profile) 

而且結帳這個要點,看看差別https://gist.github.com/astery/6137727

+0

它將從用戶表中選擇我想從配置文件表中選擇特定字段 –

+2

您的更新不正確。這是行不通的。 – zach

+0

你爲什麼這麼認爲?你試過了嗎? – Astery

4

你使用類似

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