Sorting in named_scope through 2 tables with condition

老子叫甜甜 提交于 2019-12-11 12:18:30

问题


I am looking for solution how to sort by attribute which is two association levels deep and also have an condition.

I have order model which HAS TO have association with Shop model OR Warehouse model both of these models are associated with country which has a name.

My goals are:

Scoped the orders and sort by country name.

Result has to be a ActiveRelation object

And the main goal is use this scope for MetaSearch gem for view helper sort_link

class Order < ActiveRecord::Base

  belongs_to :shop
  belongs_to :warehouse

  validate :shop_id, :presence => 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 < ActiveRecord::Base
  belongs_to :country
end

Country.coulumn_names => [:id, :name, ...]

Actualy i dont know if this is possible so I appreciate any advice.

Thanks


回答1:


You can write it like this, I have not tried it though:

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

This is assuming that you have

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

In WareHouse class.

EDIT:

Since you want to take in either warehouse country or shop country, you need a logic in select query to select the first non-null entry for country name. PostgreSQL and MySQL support function coalesce, which returns the first non-null column. You should be able to use it like this: (Again, have not tried it though)

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


来源:https://stackoverflow.com/questions/10296501/sorting-in-named-scope-through-2-tables-with-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!