Reputation: 1170
Is it possible to make a query like this? (Pseudo-code)
u=User.includes(all_delegated_attributes_from_relationships).all
How?
Further explanation:
class User<ActiveRecord::Base
has_one :car
delegate :wheel, :brake, :motor, to: :car, prefix: true
end
and then:
u=User.includes(delegated_car_parts).all
#<user id: 1, car_id: 1, name: "John", car_wheel: "foo", car_motor: "bar", car_brake: false>
I know that this can sound a little odd but I have to add a feature to an old app to export all delegated attributes from a model to CSV and this model has 14 relationships and 300 delegations... I just learnt Demeter's law when I made this app...
Upvotes: 1
Views: 4051
Reputation: 44685
There is no build-in method to do this. You could try sth like:
class User < ActiveRecord::Base
has_one :car
DelegatedCarMethods = [:wheel, :brake, :motor]
delegate *DelegatedCarMethods, to: :car, prefix: true
scope :with_car_delagations, lambda do
select_array = ["#{table_name}.*"]
select_array += DelegateCarMethods.map {|method| "#{Car.table_name}.#{method} AS car_#{method}"}
select(select_array.join(', ')).joins(:car)
end
end
But it isn't extremely pretty. Why do you need this? Calling user.wheel
or user.motor
doesn't feel right.
Upvotes: 2
Reputation: 8247
Assuming wheel, break and motor are relationships on car, you can do this:
User.includes(:car => [:wheel, :brake, :motor]).all
Upvotes: 3