Rails - HABTM关联,检查存在吗?数组中的任何对象

时间:2012-07-12 10:48:03

标签: ruby-on-rails associations has-and-belongs-to-many

我想检查数组中是否存在任何HABTM关系,如果存在则返回true。

目前,我能看到的唯一方法是:

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

有更好的方法吗?

1 个答案:

答案 0 :(得分:4)

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

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

<强>更新

尚未测试过。但这可能也有效:

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