Ryan Yang
Ryan Yang

Reputation: 69

Sort by a column in JOIN table of many-to-many relationship (rails)

I have a many to many relationship between category and post. The join table is category_post_relationships.

class Post < ActiveRecord::Base
    has_many :categories, through: :category_link_relationships
    has_many :category_post_relationships , :dependent => :destroy 
end

class Category < ActiveRecord::Base
    has_many :posts, through: :category_link_relationships
    has_many :category_post_relationships , :dependent => :destroy 
end

class CategoryPostRelationship < ActiveRecord::Base
    belongs_to :post
    belongs_to :category
end

If I have a category, the category can query for all posts by category.posts. And I want to sort these posts by the created_at of the join table category_link_relationships. There can be only one record for each category and post. I want to sort the links by the column created_at of related relationship records.

For example, post 1 was created and associated to category A. Then, the post 1 was associated to category B. Post 2 was then created and associated to category B. category B now has post 1 and post 2. I want to sort post 1 and post 2 by the created_at of the relationships, not the created_at of posts.

Thanks.

Upvotes: 1

Views: 1570

Answers (2)

port5432
port5432

Reputation: 6371

If you will always order this way, you can use a default scope on the join table.

class CategoryLinkRelationship < ApplicationRecord
  belongs_to :post
  belongs_to :category

  default_scope { order(created_at: :asc)}
end

This will be automatically picked up by ActiveRecord. Be careful, if there is also a default scope on Category it will override the sort.

Upvotes: 1

Oleh  Sobchuk
Oleh Sobchuk

Reputation: 3722

class Post < ActiveRecord::Base
    has_many :category_link_relationships , :dependent => :destroy
    has_many :categories, through: :category_link_relationships
end

class Category < ActiveRecord::Base
    has_many :category_link_relationships , :dependent => :destroy
    has_many :posts, through: :category_link_relationships
end

and now you can find posts in next way:

@category.posts.joins(:category_link_relationships).order('category_link_relati‌​onships.created_at')

Upvotes: 1

Related Questions