如何合并2个对象

时间:2013-03-14 11:17:45

标签: ruby-on-rails ruby

ruby​​ 1.8.7

@post = Post.find(1) + Post.find(2)

未定义的方法`+'用于帖子

@post = Post.find(1).merge(Post.find(2))

Post的未定义方法合并

4 个答案:

答案 0 :(得分:3)

在一次调用中将ID传递给find,如

@posts = Post.find([1, 2])

警告如果没有ID = 1或ID = 2的帖子,则会引发错误。如果您不这样做,请使用wherefind_all_by_id

@posts = Post.where(id: [1, 2])
@posts = Post.find_all_by_id([1, 2])

2之间的主要区别在于您可以使用where链接其他查询,而find_all_by_id已经返回数组,因此您无法链接查询。

答案 1 :(得分:2)

只需附加ID即可找到项目数组。所以在你的情况下它将是

@posts = Post.find(1,2)

答案 2 :(得分:1)

此外:

@posts = []
@posts << Post.find(1)
@posts << Post.find(2)

继续补充:

@posts << Post.find_all_by_id([5, 6])

甚至:

@posts << Post.all

答案 3 :(得分:1)

您可以这样做:

@posts = Post.find(1,2)

另外,我从评论中读到的内容,您想要合并@postsPost.all,两者都是数组,因此您只需使用+添加它们。

除了这个答案,我认为您不需要像@posts那样Post.all

由于@posts是一个数组,您可以简单地合并两个数组:

@posts + Post.all

或者你可以这样做:

@post | Post.all
相关问题