【发布时间】:2015-03-22 21:31:08
【问题描述】:
我有一个运行 ruby 2.1.2 和 rails 4.1.1 的 rails 应用程序,其中我有一个像这样的多态关联:
class Picture < ActiveRecord::Base
belongs_to :imageable, polymorphic: true
end
class Employee < ActiveRecord::Base
has_many :pictures, as: :imageable
end
class Product < ActiveRecord::Base
has_many :pictures, as: :imageable
end
我希望能够找到属于给定员工或没有关联“可成像”记录的所有图片。
# These both work fine
Picture.where(imageable: Employee.first) # finds all associated with Employee.first
Picture.where(imageable: nil) # finds all un-associated Pictures
#This does not work
Picture.where(imageable: [Employee.first, nil])
一旦看到运行的 SQL,它不起作用的原因就很明显了
SELECT "pictures".* FROM "pictures"
WHERE "pictures"."imageable_type" = 'Employee' AND
(("pictures"."imageable_id" = 1 OR "pictures"."imageable_id" IS NULL))
当我需要时
SELECT "pictures".* FROM "pictures"
WHERE (("pictures"."imageable_type" = 'Employee' AND "pictures"."imageable_id" = 1)) OR
"pictures"."imageable_id" IS NULL
知道如何在不写出 SQL 的情况下在 rails 中运行查询吗?
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 where polymorphic-associations null