UPDATE: Here is how we settled it. ran MYSQL Explain on the sql generated by both snippets of code:
Manifest.where(assembly_id => @assembly.id).where(part_id => @part.id).exists? NO JOINS AND RAN FASTER -- SO IT WON!
I have the following situation:
class Assembly < ActiveRecord::Base
has_many :manifests
has_many :parts, :through => :manifests
end
class Manifest < ActiveRecord::Base
belongs_to :assembly
belongs_to :part
end
class Part < ActiveRecord::Base
has_many :manifests
has_many :assemblies, :through => :manifests
end
So, as geeks do my colleagues and I got into a contentious argument about the following:
Given a part and an assembly find if they are on the same manifest.
Solution one (using associations):
@part.assemblies.include? @assembly
Solution two (using scopes):
Manifest.where(assembly_id => @assembly.id).where(part_id => @part.id).exists?
Solution one does an inner join to get the data and it drove the camp that hates spanning tables nuts. But it is terse and not ugly.
Solution two does not do an inner join and uses scopes (ie the where clauses), but it is a bit ugly.
Solution one is being called inefficient and when profiled it does in fact run a tiny bit slower.
Any thoughts on best practices for this situation.
Btw, I grabbed the code from the Rails guides in order to illustrate the issue.