Rails 4,Active Record,在belongs_to上为has_many_through创建订单范围

时间:2015-12-09 03:12:04

标签: ruby-on-rails rails-activerecord

我设置了以下型号:

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

LocationParkingLocation有一个名为upvotes的整数字段。我想创建一个'by_votes'范围,我可以将其添加到查询中,以便通过此upvotes字段对结果进行排序。在哪里以及如何定义此范围,以便我可以这样调用它:

location.parking_locations.by_votes

我无法像这样定义它,因为它不是parking_locations上的有效方法:

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

是否应在“ParkingLocation”类中定义?如果是这样,我如何告诉它我想按location_parking_locations表上的字段订购?

1 个答案:

答案 0 :(得分:1)

我想你可以在这里使用merge

您可以将范围保留在LocationParkingLocation类中,结果如下:

location.parking_locations.merge(LocationParkingLocation.by_votes)

我只是在this blog post中阅读了一些内容。