【问题标题】:How to prepend to order clause with scope如何在范围内添加订单子句
【发布时间】:2015-12-09 03:01:19
【问题描述】:

有什么方法可以添加到活动记录查询的现有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 停车位。这可能吗?

【问题讨论】:

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


    【解决方案1】:

    由于作用域是一个 lambda,你可以使用参数,例如:

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

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

    your_model.your_scope(:desc)
    

    【讨论】:

      猜你喜欢
      • 2023-01-31
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-14
      • 2019-10-22
      相关资源
      最近更新 更多