我有這些代碼在我的Rails 3.2的應用程序軌選擇與包括
User.includes(:profile).limit(10)
其選擇概況表我需要一種方法來從配置表上的特定字段選擇減少數據庫的所有字段查詢我使用 postgresql
我有這些代碼在我的Rails 3.2的應用程序軌選擇與包括
User.includes(:profile).limit(10)
其選擇概況表我需要一種方法來從配置表上的特定字段選擇減少數據庫的所有字段查詢我使用 postgresql
我想你,請問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
你使用類似
User.joins(:profile).select("users.*, profiles.field1, profiles.field2").limit(10)
的可能重複的更好 - (HTTP [Rails 3中與包含選擇?]:// stackoverflow.com/questions/4047833/rails-3-select-with-include) – Benj