Reveren Reveren - 1 month ago 7
Ruby Question

How to sort by referenced name instead of column_id

I have a list of items from a model (Records) that have a reference to a column from another model (Companies). In Records, I use

company_id
to reference the associated company. However when I sort, I don't want to use the
record.company_id
, but instead
record.company.name
. In my controller I use this to get the sort on the company_id:

@records = Record.all.order("company_id ASC")


That works just fine by sorting them by the
company_id
, but I want to sort them by the associated name. But when I do the following I get an undefined method error for name, which I know is not the correct syntax.

@records = Record.all.order(:company.name)


Q: How can I go about sorting by the associated company name?




Here is some of my corresponding code:

Record model

class Record < ActiveRecord::Base
belongs_to :company
end


Company Model

class Company < ActiveRecord::Base
has_many :records
end


Record controller (with incorrect statement)

class RecordsController < ApplicationController
def index
@records = Record.all.order(:company.name)
end
...
end


Company controller

class CompaniesController < ApplicationController
def index
@companies = Company.all
end
...
end


Record index view

...
<% @records.each do |record| %>
<tr>
<td><%= record.company.name %></td>

Answer

Here is what you are looking for:

Record.includes(:company).order('companies.name') # no need to call `all`

Check out Active Record Query Interface Giude for more info.

Comments