mysql - Rails 4 - how to use "includes(:model)" with ".select(...)"? Is there any alternative? -
i have 3 tables 45+ columns each. here models:
class product < activerecord::base belongs_to :manufacturer belongs_to :team end class manufacturer < activerecord::base has_many :products end class team < activerecord::base has_many :products end i need fetch projects @ stages, so:
@products = product.where('products.stage != 3 , products.stage != 4 , products.stage != 5') .order(sort_column + " " + sort_direction) but - n+1 problem occur, so:
@products = product.includes(:team, :manufacturer) .where('products.stage != 3 , product.stage != 4 , products.stage != 5') .order(sort_column + " " + sort_direction) but because tables have 135+ columns , fetching of them ineffective - more need 10 columns (6 products, 2 teams , 2 manufacturers), wanted use .select(...) specify fields need.
but found out there's no way use eager loading (includes(...)) .select(...).
what can now? there other approach? i've tried write raw sql query, don't know how re-write includes(...) part.
thank in advance.
this solution fires 1 query per association, selects necessary columns. unable find solution selected desired columns in 1 query.
firstly, introduce new associations select columns care about:
# class product # change names make sense in app. belongs_to :manufacturer # doesn't change belongs_to :team # doesn't change belongs_to :simple_team, -> { select(:id, :other_team_columns) }, class_name: "team" belongs_to :simple_manufacturer, -> { select(:id, :other_manufacturer_columns) }, class_name: "manufacturer" then preload them in product query (eager_load ignored select overrides in testing [rails 4.2.3]):
# fires 3 queries, 1 each products, teams , manufacturers, # teams , manufacturers have desired columns selected. @products = product.preload(:simple_team, :simple_manufacturer) .where('products.stage != 3 , product.stage != 4 , products.stage != 5') .order(sort_column + " " + sort_direction) finally, use new associations in view:
@products.each |product| product.simple_team.name product.simple_manufacturer.name end
Comments
Post a Comment