Rails 处理单个和多个返回对象
在 Rails 中你可以使用 .each do ||循环查询的返回结果。但是如果只返回一行怎么办?或者你有 0、1 或多个的可能性?如何处理这些场景而不引发错误?
这种情况尤其是我接受 ryan 的 Railcast 博客之后的嵌套属性 (http://railscasts.com/episodes/196-nested-model-form-part-1)
我可以返回 1 个或多个嵌套项目,然后我需要循环遍历并编写 XML 表单。
In rails you can use .each do || to loop through the returned results of a query. But what if only one line is returned? or you have the possibility of 0, 1, or many? how do you handle these scenarios without throwing an error?
This situation in particular is one where i am accepting nested attributes following ryan's railcast blog (http://railscasts.com/episodes/196-nested-model-form-part-1)
I can have 1 or many nested items being returned which I then need to loop through and write an XML form.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您使用
#each
循环访问一组结果时,您无需担心返回了多少结果。如果为零,则数组中不会有任何元素传递给循环;如果有的话,只有一个。如果更多,则将每个都传递到循环。在每种情况下,只要您只是循环数组,无论数组是否为空,或者是否有一千个元素,相同的循环代码都将运行而不会出现错误。通过示例,我可以毫无问题地循环具有不同数量元素的数组:
When you're looping through a set of results with
#each
, you don't need to worry about how many results were returned. If zero, there won't be any elements in your array to pass to the loop; if one, only one. If more, then each is passed to the loop. In each case, as long as you're just looping over an array, it doesn't matter if the array is empty, or if it has a thousand elements, the same loop code will run without an error.By means of example, I can loop over arrays with different numbers of elements without any issue: