0

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.

RidingRails
  • 782
  • 3
  • 7
  • 21

1 Answers1

0

I would do it one of the following 2 ways, not for performance reasons, just for clarity of expression:

Are there any manifests belonging to @assembly and @part?

Manifest.where(assembly_id: @assembly.id, part_id: @part.id).any?

Or, do @assembly and @part share any manifests?

(@assembly.manifests & @part.manifests).any?
AJcodez
  • 31,780
  • 20
  • 84
  • 118