Rails Active Record 查找所有内容,包括重复项
如何在我的视图中获得重复的帖子?
我希望能够执行这样的操作:
@post = post.find(1,2,1)
返回 post 1 、 post 2 ,然后返回 post 1 (再次)。
意识到这是一个愚蠢的问题,但我找不到任何文档。
How can I get duplicate posts in my view?
I want to be able to do something like this:
@post = post.find(1,2,1)
to return post 1 , post 2 and then post 1 (again).
realize this is a dumb question but I can't find any documentation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然我不确定用例,但您可以执行以下操作:
您可以在 Post 模型中定义它:
显然,上面的方法效率低下,因为您正在进行许多 SQL 调用。如果你希望它高效,那么你可以编写一段代码,进行一个 sql 调用(但不会返回重复项),然后迭代数组并重新排列(复制重复项),例如(未完全测试):
这个应该更好因为您只对数据库进行一次调用(通常是最慢的部分),但是它是 O(N^2) 如果需要,可能有一种方法可以使其成为 O(N) 。然而,它比之前的选项有了很大的改进
Although I'm not sure about the use case you can do something like:
of you can define this in your Post model:
Obviously the above is inefficient as you are making many SQL calls. If you want it efficient then you can write a code that makes one sql call (but will not return duplicates) and then iterate through the array and rearrange (with copying for duplicates) such as (not fully tested):
This one should be better as you are only making one call to DB (normally slowest part) however it's O(N^2) There might be a way to make it O(N) if need be. However It's great improvement from the previous option
在不了解更多细节的情况下,这就是我的建议。看看这篇关于复选框数组的文章: http://www .skuunk.com/2008/05/checkbox-arrays-in-rails.html
每个复选框都会将一个值放入特定的 params 键中。这将解决获取包含值列表的数组的问题。如果这不能解决您的特定问题,请在评论中告诉我。
Without knowing more detail, here's what I would advise. Take a look at this post regarding checkbox arrays: http://www.skuunk.com/2008/05/checkbox-arrays-in-rails.html
Each checkbox drops a value into a particular params key. This will solve the problem of getting an array with a list of values. Let me know in the comments if this doesn't resolve your particular issue.