Rails: order using a has_many/belongs_to relationship

后端 未结 2 400
谎友^
谎友^ 2021-02-07 07:12

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 colum         


        
2条回答
  •  情歌与酒
    2021-02-07 08:13

    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.

提交回复
热议问题