Search code examples
ruby-on-railsscopemodel-associations

Scope associated models by "created_at"


I have three models : User, Product and Ownership. An ownership has a product_id:integer and a user_id:integer. I want to scope my products by created_at DESC.

app/models/product.rb

        .
        .
        .
default_scope -> { order('products.created_at DESC') }
        .
        .
        .

But when I do user.owned_products, it's not ordered like created_at DESC. How can I do that ? Must I add a scope in my user model ?

Here is the relationship between my users and products :

app/models/user.rb

        .
        .
        .
has_many :ownerships
has_many :owned_products, through: :ownerships,
                          source: :product
        .
        .
        .

Solution

  • To set the order on a user's owned products, you can specify this in the association. For example:

    has_many :owned_products, through: :ownerships,
                              source: :product,
                              order: "created_at DESC"