如何在OR条件下组合两个ActiveRecord :: Relation来形成活动关系?

时间:2014-10-12 14:37:51

标签: ruby-on-rails activerecord active-relation

此链接为great,但未解决在条件下合并两个活动关系后获取active_relation的问题。还有其他links但是 没有人回答上述问题。虽然and方法merge起作用并且提供了积极的关系,但我找到了解决or两种情况的方法的困境。为了阐明我的问题,假设我必须两个不同的书面查询,而不是单独执行并添加不输出活动关系的查询。 例如: -

@incoming = Message.incoming_from_my_friends_only(@current_user) # where 'incoming_from_my_friends_only' is a active record query  
@outgoing = Message.outgoing_to_my_friends_only(@current_user) # same here

现在,我不想这样做

@incoming = Message.incoming_from_my_friends_only(@current_user) 
@outgoing = Message.outgoing_to_my_friends_only(@current_user)

@messages = @incoming + @outgoing

虽然这样做不是问题,但我宁愿将结果置于活动关系中,以便我可以执行任何进一步的活动记录查询。

任何想法......或者更好地解决我的问题?

修: -

我正在查看个人资料,发现这个问题没有任何活动,甚至没有评论,即使它可能被证明是至关重要的。我这样说是因为在AR上执行非常简单,如使用合并方法在第二个链接中所示,但或为什么?不应该是rails社区的pro提供这种方法???

1 个答案:

答案 0 :(得分:0)

我后来发现了一种方法,可以在条件下结合两个活动关系但不是我想要的答案 - 有一种方法可以在活动关系上执行 merge。   答案我发现是这个。

# replace the comment part in where by the condition written for incoming_from_my_friends_only and outgoing_to_my_friends_only respectively
@incoming = Message.where("(#incoming_from_my_friends_only(@current_user)) or (outgoing_to_my_friends_only(@current_user))")