PlankTon
PlankTon

Reputation: 12605

How to get first model from collection?

I have a collection which returns a model for each date within a given range (fed in through a Rails controller).

In my view for the collection, I'd like to display the month for the first date from the collection...I'm just wondering what the most elegant way of achieving that is?

It seems the most straightforward would be to access the array of models via the collection, nab the first one, and run the required method within that model to retrieve the month name. Seems straightforward, but I can't figure out how to nab the first model from within the collection.

Alternatively, I could pass the required value in through the call to router() from rails, but that seems a little ugly.

Finally, I could do up an entirely new collection just to retrieve that one value, but again - seems excessive.

Any suggestions on how I should go about doing this? Assuming it's not too much of a taboo to feed model data back into a collection, I guess I'm asking how to do that.

Upvotes: 18

Views: 22199

Answers (2)

Ivan Castellanos
Ivan Castellanos

Reputation: 8243

collection.at(0) //etc

But if you have to check if there is at least one element

if(collection.length){
    collection.at(0) //etc
}

Upvotes: 8

djlumley
djlumley

Reputation: 2967

Backbone.js collections have access to Underscore.js methods.

MyCollection.first() should return the first model from a collection.

Upvotes: 52

Related Questions