2012-07-12 104 views
2

我想检查数组中是否存在任何HABTM关系,并返回true(如果存在)。Rails - HABTM关联,检查是否存在?数组中的任何对象

目前,我可以看到这样做的唯一途径是:

result = false 
[1,2,3,4].each do |i| 
    if user.parents.exists?(i) 
    result = true 
    break 
    end 
end 

我试图传递一个数组如下,但我得到一个异常

result = true if user.parents.exists?([1,2,3,4]) 

NoMethodError: undefined method `include?` for 1:Fixnum 

有没有更好的这样做的方式?

回答

3
[1,2,3,4].inject(false) {|res, i| res ||= user.parents.exists?(i)} 

几乎相同的逻辑,只是更多的ruby-ish代码使用注入语法。

UPDATE:

没有测试它。但是这也可能起作用:

user.parents.exists?(:id => [1,2,3,4]) 
+1

更新后的版本起作用。我更喜欢使用注入,更可读。谢谢=] – bdx 2012-07-12 11:29:18

+1

更新版本为我工作。 – 2014-06-27 20:01:27

相关问题