Rails - Sort by join table data

前端 未结 6 1875
庸人自扰
庸人自扰 2020-12-05 07:03

I\'ve got a RoR project in the works. Here are the applicable sections of my models.

Home

has_many :communities, :through => :ava         


        
6条回答
  •  眼角桃花
    2020-12-05 07:45

    You can also sort linked tables like this (e.g.):

    class User
      has_many :posts
    end
    
    class Post
      belongs_to :user
    
      scope :sorted_by_user_and_title, -> { 
        joins(:user).merge(
         User.order(first_name: :asc, last_name: :asc)
        )
        .order(title: :desc)
        # SELECT * FROM `posts`
        # INNER JOIN `users` ON `posts`.`user_id` = `users`.`id`
        # ORDER BY
        # `users`.`first_name` ASC, `users`.`last_name` ASC, `posts`.`title` DESC;
      }
      scope :sorted_by_title_and_user, -> { 
        order(title: :desc)
        .joins(:user).merge(
         User.order(first_name: :asc, last_name: :asc)
        )
        # SELECT * FROM `posts`
        # INNER JOIN `users` ON `posts`.`user_id` = `users`.`id`
        # ORDER BY
        # `posts`.`title` DESC, `users`.`first_name` ASC, `users`.`last_name` ASC;
      }
    end
    

    Regards

提交回复
热议问题