0

A User has many Airports though Preferences.

I want to display the airports, sorted by "first added" to their preferences. How do I do this? Since the airports are a "static" database, their created_date is irrelevant. We're looking more for something like associated_date.

I suppose what I need to do is find the association in the join table and get its created_date.

I'm sure I can figure it out. But, does anyone have the solution close at hand?

Thanks.

Jonathan Tuzman
  • 11,568
  • 18
  • 69
  • 129
  • When you say "I want to display the airports", you mean the `airports` that are associated with the `user` through the user's `preferences`, yes? – jvillian Mar 06 '19 at 23:22

2 Answers2

1

Are you looking for something like this?

Preference.where.not(airport_id: nil).order(created_at: :asc)

This would give you back all instances of Preference with an airport_id in ascending order.

Additionally, this may help you out too:

Rails order by association field

An approach based on this link would be this:

Airport.joins(:preferences).merge(Preference.order(created_at: :asc))

This is assuming you have a traditional has many through association set up between User, Airport, and Preference.

vinyl
  • 490
  • 4
  • 8
1

Assuming that you want the airports for the @current_user sorted by the created_at date of the preferences that join the airports to the @current_user (whew!)...

And assuming that:

class Airport < ApplicationRecord
  has_many :preferences
end

I believe you want something like:

@current_user.aiports.joins(:preferences).order(preferences: {created_at: :asc})

or :desc, depending on your needs.

That's not tested, so you may need to fiddle with it a bit.

jvillian
  • 19,953
  • 5
  • 31
  • 44