问题
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