I have 3 models which are connected like this:
class FooTemplate < ActiveRecord::Base
has_many :foos
end
class Foo < ActiveRecord::Base
belongs_to :foo_template
belongs_to :bar
end
class Bar < ActiveRecord::Base
has_many :foos
end
Inside the Barmodel I want a method that finds all Bars that have Foos that belong to each FooTemplate referenced by the ids in the array:
def find_by_foo_templates(foo_template_ids)
# what goes here?
end
The parameter is an array which has always the following form:
[""]
["", "1", "2"]
The array always contains an empty string even if no ids are submitted.
I hope you understand what I am trying to do.
Update
Let me show you an example:
Bar: 1
Foo: 1
FooTemplate: 1
Foo: 2
FooTemplate: 2
Bar: 2
Foo: 3
FooTemplate: 2
Foo: 4
FooTemplate: 3
Bar: 3
Foo: 5
FooTemplate: 3
Foo: 6
FooTemplate: 4
This shall be 3 Bars each with 2 independent Foos. And the Foos have some "overlapping" FooTemplates.
Now the desired results for some lists:
["1"] schould only return Bar 1, because it's the only one whose Foos have a FooTemplate 1.
["2"] should return Bar 1 & 2, because they both have a Foo with a FooTemplate 2
["2", "3"] should return only Bar 2, because it's the only one which has a Foo with FooTemplate 2 AND a Foo with FooTemplate 3
["1", "4"] should return nothing because there is no Bar whose Foos have FooTemplates 1 AND 4
Update 2
I have found a solution that works, but it uses reject and it produces some more database queries:
class Bar < ActiveRecord::Base
has_many :foos
has_many :foo_templates, through: :foos
def self.find_by_foo_template_ids(foo_template_ids)
ids = foo_template_ids.map { |id| id.to_i }
joins(foos: :foo_template).uniq.where(foos: { foo_template_id: ids }).reject do |bar|
!(bar.foo_template_ids & ids == ids)
end
end
end
And this returns an array, but I would like to have an ActiveRecord::Relation to perform additional queries on it.