Take the 2-minute tour ×

I have 2 Rails 4.0 Models :

    class Article 
        has_many :comments

    class Comment
        belongs_to :article
        scope :created_desc, :order => "created_at DESC"

The behaviour i'm looking for is being able to sort the comments of an article by the created scope.

However this code

    article = Article.find(1)

triggers a new SQL query to be ran :

    SELECT "comments".* FROM "comments" ORDER BY created_at DESC

I would expect, considering the code runs the scope on the comments of the article, to only get the comments that belong_to that article, however, I get all comments.

This is quite counter intuitive i find. Can anybody suggest the right way to do this ? Something tells me that adding another scope on comments that filteres by Article id is a method that would be scoffed at. So what would be the proper way?

Anticipated thanks

share|improve this question
add comment

2 Answers

The problem is, that scopes without usage of lambda (=> lazy evaluation) are deprecated and seem to produce strange behaviour in Rails 4. This works, just tested both ways in a Rails 4 app:

scope :created_desc, lambda { order('created_at DESC') }
share|improve this answer
add comment

you can use the -> too.

scope :created_desc, -> { order('created_at DESC') }
share|improve this answer
add comment

Your Answer


