Join GitHub today
GitHub is home to over 31 million developers working together to host and review code, manage projects, and build software together.Sign up
Sorting by an association's field #13
I would like to be able to, e.g., pass in 'sorts = "user_name asc"' to sort by the user's name field.
Shouldn't be too hard to implement, should it? Checking the logs, the join to the associated table already gets performed, so I'm assuming it'd be trivial to pass in the association's field name in the order(...) call as well?
I can't quite seem to get sorting to work by an associated record's field. Is it possible, and if so, what am I missing?
class Vehicle < ActiveRecord::Base belongs_to :location end class Location < ActiveRecord::Base has_many :vehicles validates_presence_of :name end
This works fine:
%th= sort_link @q, :location_id, Vehicle.human_attribute_name(:location)
But I'd really like to do this:
%th= sort_link @q, 'location.name', Vehicle.human_attribute_name(:location)
I'd really appreciate any help or guidance! Thanks!
sorry for asking here, but would one of you mind helping me about this sort_link?
This was referenced
Jan 14, 2015
Jan 14, 2015
@jonatack No that's not necessarily correct - the sort link string is not a 1-1 mapping to an order clause spelling out sql. It's a relation name, which may be a different table. The documentation had me going totally the wrong direction on this. The association section says,
'Please note that in a sort link, the association is expressed as an SQL string ('employees.last_name') with a pluralized table name, instead of the symbol :employee_last_name syntax with a class#underscore table name used for Ransack objects elsewhere.'
This appears to not be accurate. In my case, I have a Request model that belongs_to a State model, which has a name attribute. I was lead to believe by that statement that I should use:
But found it only worked when I changed it to:
Aug 21, 2015
Thanks for clarifying the docs @jonatack!
I wasn't sure if that still worked for a field of an association's association (A -> B-> C.field) and it does. lib/ransack/adapters/active_record/context.rb#L209 seems to be the method responsible for that.