我怎样才能有条件地调用ActiveRecord中的属性?

时间:2015-08-27 17:32:48

标签: ruby-on-rails ruby-on-rails-3 activerecord

我有一段代码如下:

foreign_object = (some_test) ? nil : <some foreign_object>

Document.where(foreign_id: foreign_object, status: "Working", ... )

如果foreign_object为nil,则只能找到foreign_id = NULL的Documents。有没有办法有条件地将foreign_id放入?我基本上想写:

Document.where(foreign_id: foreign_object if foreign_object, status: "Working", ...)

1 个答案:

答案 0 :(得分:4)

我在这种情况下这样做:

 documents = Document.where(status: 'working')
 documents = documents.where(foreign_id: foreign_object) if foreign_object