Rails 处理单个和多个返回对象

发布于 2024-09-17 22:54:48 字数 341 浏览 4 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

恏ㄋ傷疤忘ㄋ疼 2024-09-24 22:54:48

当您使用 #each 循环访问一组结果时,您无需担心返回了多少结果。如果为零,则数组中不会有任何元素传递给循环;如果有的话,只有一个。如果更多,则将每个都传递到循环。在每种情况下,只要您只是循环数组,无论数组是否为空,或者是否有一千个元素,相同的循环代码都将运行而不会出现错误。

通过示例,我可以毫无问题地循环具有不同数量元素的数组:

ree-1.8.7-2010.02 > [].each {|e| puts e }
 => []
ree-1.8.7-2010.02 > [1].each {|e| puts e }
1
 => [1]
ree-1.8.7-2010.02 > [1,2,3].each {|e| puts e }
1
2
3
 => [1, 2, 3]

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:

ree-1.8.7-2010.02 > [].each {|e| puts e }
 => []
ree-1.8.7-2010.02 > [1].each {|e| puts e }
1
 => [1]
ree-1.8.7-2010.02 > [1,2,3].each {|e| puts e }
1
2
3
 => [1, 2, 3]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文