0
votes

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}]}

1
You would like to sort by sum of integers of by what? Get the instance, please, what are you really want - Ilya
Hello! I have a list of Items inside Collection, I want to sort the Items which are inside the Collection by number - lapinkoira
So you want to query your collections and receive them with sorted items ? What are the items ? A different model backed by a different table ? If that is the case, Collection.all should return you your collections without the corresponding items - VonD
I updated how I am rendering the collections, I include the items and I want those items get sorted by a item's field called number. - lapinkoira
I want to order them from ascendent order, from smaller to greater. - lapinkoira

1 Answers

1
votes

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