1

I'm wondering how to join up two different models, and then sort them by via another associated model.

Say I've got an ACCOUNT, that has_many CARS and BIKES, and they both have a polymorphic relation (has_one) to a WHEELSET.

How would I write a query to select all bikes and cars for a given account, and have them sorted by the wheelset (or another column in the wheelset model?)

Account
has_many :cars, :bikes

Bike
belongs_to :account
has_one wheelset, :as => wheelable

Car
belongs_to :account
has_one wheelset, :as => wheelable

Wheelset
belongs_to :wheelable, :polymorphic => true

I'm thinking something like the following, (which doesn't work unfortunately)

a = Account.first
sets = a.bikes.includes(:wheelset) + self.cars.includes(:wheelset)
sets.order('wheelset.wheels ASC')

1 Answer 1

3

You could build an standard Ruby array and use the array sort method to order them.

a = Account.first
sets = Array.new
sets += a.bikes + a.cars
sets.sort! { |a, b| a.wheelable <==> b.wheelable }

I havent tested this but its roughly how I would go about it given this situation.

Sign up to request clarification or add additional context in comments.

1 Comment

Correct. Was on a tiny netbook. Could barely read the screen :D /excuse

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.