如何从收藏中获得第一个模型?
我有一个集合,它返回给定范围内每个日期的模型(通过 Rails 控制器输入)。
在我对集合的看法中,我想显示集合中第一次约会的月份......我只是想知道实现这一点的最优雅的方式是什么?
似乎最简单的方法是通过集合访问模型数组,获取第一个模型,然后在该模型中运行所需的方法来检索月份名称。看起来很简单,但我不知道如何从集合中获取第一个模型。
或者,我可以通过从 Rails 调用 router() 来传递所需的值,但这看起来有点难看。
最后,我可以创建一个全新的集合只是来检索该值,但同样 - 似乎太过分了。
关于我应该如何去做这件事有什么建议吗?假设将模型数据反馈到集合中并不是太禁忌,我想我是在问如何做到这一点。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Backbone.js
集合可以访问Underscore.js
方法。MyCollection.first()
应该返回集合中的第一个模型。Backbone.js
collections have access toUnderscore.js
methods.MyCollection.first()
should return the first model from a collection.但如果你必须检查是否至少有一个元素
But if you have to check if there is at least one element