I have a rails app running ruby 2.1.2 and rails 4.1.1 and in it I have a polymorphic association like so:
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
I want to be able to find all Pictures that either belong to a given Employee or have no associated "imageable" record.
# 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])
The reason it does not work is obvious once you see the SQL that is run
SELECT "pictures".* FROM "pictures"
WHERE "pictures"."imageable_type" = 'Employee' AND
(("pictures"."imageable_id" = 1 OR "pictures"."imageable_id" IS NULL))
When instead I need
SELECT "pictures".* FROM "pictures"
WHERE (("pictures"."imageable_type" = 'Employee' AND "pictures"."imageable_id" = 1)) OR
"pictures"."imageable_id" IS NULL
Any idea how to run the query in rails without writing out the SQL?