flyingL123
flyingL123

Reputation: 8106

Rails 4, Active Record, create order scope on belongs_to for has_many_through

I have the following models set up:

class Location < ActiveRecord::Base    
  has_many :location_parking_locations
  has_many :parking_locations, through: :location_parking_locations
end

class LocationParkingLocation < ActiveRecord::Base
  belongs_to :location
  belongs_to :parking_location
end

class ParkingLocation < ActiveRecord::Base
  has_many :location_parking_locations
  has_many :locations, through: :location_parking_locations
end

The LocationParkingLocation has an integer field called upvotes. I would like to create a 'by_votes' scope that I can add to a query to order the results by this upvotes field. Where and how do I define this scope, so that I can call it like this:

location.parking_locations.by_votes

I can't define it like this, because then it's not a valid method on parking_locations:

class LocationParkingLocation < ActiveRecord::Base
  belongs_to :location
  belongs_to :parking_location
  scope :by_votes, -> { order("upvotes DESC") }
end

Should it be defined in the 'ParkingLocation' class? If so, how do I tell it that I want to order by a field on the location_parking_locations table?

Upvotes: 1

Views: 56

Answers (1)

dinjas
dinjas

Reputation: 2125

I think you might be able to use merge here.

You can leave your scope in the LocationParkingLocation class, and the result would look like:

location.parking_locations.merge(LocationParkingLocation.by_votes)

I just read a little about it in this blog post.

Upvotes: 1

Related Questions