有没有办法预先添加到活动记录查询的现有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
停车位。这可能吗?
答案 0 :(得分:0)
由于范围是lambda,因此可以使用参数,例如:
scope :your_scope, -> (sort_order = :desc) { order(name: sort_order) }
只需根据需要进行设置,并使用(可能是可选的)参数调用它:
your_model.your_scope(:desc)