Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 - Select using eager_load

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?

like image 980
developer033 Avatar asked Jun 20 '16 13:06

developer033


Video Answer


1 Answers

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')
like image 74
Fabian Winkler Avatar answered Oct 03 '22 23:10

Fabian Winkler