Rails: order using a has_many/belongs_to relationship

12,803

Solution 1

You need to join the related table to the request.

@result = DogTag.find(:all, :joins => :dog, :order => 'dogs.name')

Note that dogs is plural in the :order statement.

Solution 2

In Rails 4 it should be done this way:

@result = DogTag.joins(:dog).order('dogs.name')

or with scope:

class DogTags < ActiveRecord::Base
  belongs_to :dog
  scope :ordered_by_dog_name, -> { joins(:dog).order('dogs.name') }
end
@result = DogTags.ordered_by_dog_name

The second is easier to mock in tests as controller doesn't have to know about model details.

Share:
12,803

Related videos on Youtube

Author by

Evan

Updated on April 21, 2022

Comments

  • Evan about 1 year

    I was wondering if it was possible to use the find method to order the results based on a class's has_many relationship with another class. e.g.

    # has the columns id, name
    class Dog < ActiveRecord::Base
      has_many :dog_tags
    end
    # has the columns id, color, dog_id
    class DogTags < ActiveRecord::Base
      belongs_to :dog
    end
    

    and I would like to do something like this:

    @result = DogTag.find(:all, :order => dog.name)
    

    thank you.

  • Staelen
    Staelen over 13 years
    should be DogTag.find(:all, :joins => :dog, :order => 'dogs.name') =)
  • Evan over 13 years
    Thank you for the solution. I'm sure you know, but for anyone else, I found that the order had to be the table name as well, i.e. I had to pluarlize it: 'dogs.name' not 'dog.name'
  • Junchao Gu
    Junchao Gu about 7 years
    I tried the first but it did not work. Instead this works: @result = DogTag.joins(:dog).order('name'). I am using PostgreSQL, not sure if it is related
  • Simon Franzen
    Simon Franzen about 5 years
    DogTab.where(...).joins(:dog).order('dogs.name') yeah ! Thanks !