在named_scope中通过2个带有条件的表进行排序

我正在寻找解决方案如何按属性排序,这是两个关联级别深,也有一个条件。

我有与商店模型或仓库模型有关联的订单模型这两个模型都与有名称的国家相关联。

我的目标是:

缩小订单并按国家/地区名称排序。

结果必须是ActiveRelation对象

主要目标是将此范围用于MetaSearch gem for view helper sort_link

class Order  true, :if => "warehouse_id.nil?" validate :warehouse_id, :presence => true, :if => "shop_id.nil?" #the case with shop_id.present? && warehouse_id.present? does not exist scope :sort_by_country_name, ??? end class Shop < ActiveRecord::Base belongs_to :country end class Warehouse  [:id, :name, ...] 

Actualy我不知道这是否可能所以我感谢任何建议。

谢谢

你可以这样写,我还没试过:

 scope :sort_by_warehouse_country_name, joins(:warehouse).order('warehouse.country_name DESC') 

这假设你有

 delegate :name, to: :country, prefix: true 

在WareHouse类中。

编辑:

由于您要接收仓库国家/地区或商店国家/地区,因此您需要选择查询中的逻辑来选择国家/地区名称的第一个非空条目。 PostgreSQL和MySQL支持函数coalesce ,它返回第一个非空列。 你应该能够像这样使用它:(再次,虽然没有尝试过)

 def self.sort_by_country_name Order.select("COALESCE(warehouse.country_name, shop.country_name) as country_name").joins(:warehouse, :shop).order("country_name DESC") end