lapinkoira
lapinkoira

Reputation: 8978

Rails order active record by foreign attribute

I have those queries:

@collections = Collection.all()
render :json => @collections.as_json(
              :include => :items
            )

and

@collection = Collection.find(params[:id])

For LIST and GET methods. And a Collection has zero or many Items. I defined the relationship with belong_to field in Items and has_many field in Collection and that's working fine.

Then when I query the collections and render the JSON I would like to sort the items by an integer variable called number which belongs to Item.

I tried this but it's not working:

@collections = Collection.sort_by &:item_number

I want to sort the list of Item which is inside the Collection by number. This is what @collections = Collection.all() returns, and I would like to sort the list of Items by number.

{"id":1,"title":"Collection","plot":"arrow","created_at":"2016-04-11T17:53:38.892Z","updated_at":"2016-04-11T17:53:38.892Z", "item":[{"id":10,"title":"Item 12","collection_id":1,"created_at":"2016-04-11T23:27:08.302Z","updated_at":"2016-04-11T23:27:08.302Z","number":12},{"id":11,"title":"Item 102","collection_id":1,"created_at":"s2016-04-11T23:27:24.649Z","updated_at":"2016-04-11T23:27:24.649Z","number":10},{"id":12,"title":"Item 9","collection_id":1,"created_at":"2016-04-11T23:27:53.201Z","updated_at":"2016-04-11T23:27:53.201Z","number":9}]}

Upvotes: 0

Views: 317

Answers (1)

Abdoo Dev
Abdoo Dev

Reputation: 1276

You can add order to your has_many relation in the Collection model

has_many :items, -> { order(:number) }

That will give you the list of items inside the collection sorted by number

Upvotes: 1

Related Questions