Cosmin
Cosmin

Reputation: 2080

Rails (4) scope on child model returning all records

I have 2 Rails 4.0 Models :

    class Article 
        has_many :comments
    end 


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

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)
    article.comments.created_desc 

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

Upvotes: 0

Views: 462

Answers (2)

d34n5
d34n5

Reputation: 1318

you can use the -> too.

scope :created_desc, -> { order('created_at DESC') }

Upvotes: 1

lawitschka
lawitschka

Reputation: 745

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') }

Upvotes: 3

Related Questions