如何在范围前添加到订单子句

时间:2015-12-09 03:01:19

标签: ruby-on-rails ruby-on-rails-4 rails-activerecord

有没有办法预先添加到活动记录查询的现有order部分?

我在Location模型上定义了以下关联:

class Location < ActiveRecord::Base    
  has_many :location_parking_locations, -> { by_votes }
  has_many :parking_locations, through: :location_parking_locations
end

LocationParkingLocation模型中,定义了by_votes范围:

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

我想在ParkingLocation模型中添加一个范围,为查询添加一个额外的范围,但我希望该范围可以预先添加到查询的现有order部分。范围如下:

class ParkingLocation < ActiveRecord::Base
  has_many :location_parking_locations
  has_many :locations, through: :location_parking_locations
  scope :with_pending, -> { order(creation_pending: :desc) }
end

我希望打电话给location.parking_locations.with_pending,然后取回一系列parking_locations,按照投票顺序排列,但在收集开头有任何pending停车位。这可能吗?

1 个答案:

答案 0 :(得分:0)

由于范围是lambda,因此可以使用参数,例如:

scope :your_scope, -> (sort_order = :desc) { order(name: sort_order) }

只需根据需要进行设置,并使用(可能是可选的)参数调用它:

your_model.your_scope(:desc)