I'm trying to select only certain columns using eager_load
, but I'm facing the problem that it cancels my 'select'.
Model:
class Timeline < ActiveRecord::Base
belongs_to :timeline_category, foreign_key: :timeline_category_id
belongs_to :user, foreign_key: :user_id
scope :with_relations, -> { eager_load(:timeline_category).eager_load(:user).order(created_at: :desc)
end
Query:
Timeline.select('timelines.*, users.username, timeline_categories.icon').eager_load(:timeline_category).eager_load(:user)
I tried also:
Timeline.select('timelines.*, users.username, timeline_categories.icon').with_relations
For some reason, it keeps selecting all columns of all 3 tables. How can I fix it?
Rails 5 introduced the left_outer_joins method. So it's finally possible:
Timeline.left_outer_joins(:timeline_category, :user)
.select('timelines.*, users.username, timeline_categories.icon')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With