Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort by created_at column of association in rails?

Here are my associations:

Class Post
belongs_to :user
has_many :favorites, :dependent => :destroy
has_many :favoriters, :through => :favorites, :source => :user
end

Class User
has_many :posts
has_many :favorites,  :dependent => :destroy
has_many :favorited, :through => :favorites, :source => :post
end

Class Favorites
belongs_to :user, :post
end

I want to sort users' favorite posts by the created_at column of the Favorites association. However, this sorts by the Post created_at attribute, not the Favorites created_at attribute. How can I sort by the Favorites created_at attribute?

 @[email protected]('created_at DESC')
like image 485
John C Avatar asked May 14 '12 16:05

John C


People also ask

What is ORM in ror?

1.2 Object Relational Mapping Object Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system.

How does Active Record work?

ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

What is Active Record ORM?

ORM - Object Relational Mapping provides a variety of frameworks and techniques that are helpful in working with Relational Databases such as MySQL, PostgreSQL, etc. “Active record - an object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.”


2 Answers

You need to specify which table you want to use in the order by clause.

@posts = @user.favorited.order('posts.created_at DESC')

ought to do it.

One nice trick is to use the rails console when inspecting associations. Specifically, it helps to use the 'to_sql' method on Active Record queries you are performing.

For instance:

% bundle exec rails console

> u = User.last
> u.favorited.order('created_at DESC').to_sql
like image 175
ipd Avatar answered Nov 15 '22 20:11

ipd


use this in your post model for set default order:

default_scope { order("created_at DESC") }
like image 34
Zakaria Avatar answered Nov 15 '22 21:11

Zakaria