How to order a set of objects based on association attributes in Ruby on Rails? -
in ruby on rails application, have model has number of one-to-one associations other models. let's each instance
belongs region
, country
, , city
. have selected couple of instance
using scope
, want order them based on name
attributes of region
, country
, , city
models not part of instance
model itself.
the thing want show selected instances
on index action of activeadmin page region
, country
, , city
, , accordingly, want have them sorted in order.
it's straightforward order collection attributes on 1 or more associations—join on associations , order attributes. verbose way this:
instance.joins(:region, :country, :city). order("regions.name desc"). order("countries.name desc"). order("cities.name desc")
but recommend writing these conditions scopes on models. can change , reuse them more easily.
class instance < activerecord::base scope :ordered, -> joins(:region, :country, :city). merge(region.ordered). merge(country.ordered). merge(city.ordered) end end class region < activerecord::base scope :ordered, -> order(name: :desc) end end class country < activerecord::base scope :ordered, -> order(name: :desc) end end class city < activerecord::base scope :ordered, -> order(name: :desc) end end
the magic here in merge
method, documented here.
put like
@instances = instance.ordered
Comments
Post a Comment