Is "has_many ... :through" faster?

I have a table which maps users to photo album as hosts:

   > Album table | => | Hosts | <=> | Users |

Sometimes I need to query if a user is a host of an album:

   if album.hosts.include? user

Which I cannot do because "hosts" is an array of Host models -- not users. I was wondering which solution be faster, or perform better.


   has_many :host_users, :through => :hosts, :source => :user


   def host_users

      # Create table as instance variable       if !@hostUsersTbl          hosts.each do |h|             @hostUsersTbl[] = h          end       end

      @hostUsersTbl    end

The first solution would make an extra call to the DB, but the second is manually creating the list. I guess I could also do this instead:

   has_and_belongs_to_many :hosts, :class_name => "User", :join_table => "hosts"

But then I wouldn't have the Host model array to manipulate (i.e. create, delete), right? Please advise.

Thanks, Jeremy

Hey Jeremy, The way I'd do this is with a

has_many :users, :through => :hosts

I'm of course presuming that the Host model belongs to album and user, and of course that you already have the has_many :hosts in both user.rb and album.rb if not classes should look like

class Album<ActiveRecord:Base   has_many :hosts   has_many :users, :through => :hosts end

class User<ActiveRecord:Base   has_many :hosts   has_many :albums, :through => :hosts end

class Host<ActiveRecord:Base   belongs_to :user   belongs_to :album end

I think this would be faster as it will only call the database when it is needed so it won't overload your objects or your database with unnecessary transactions.

Hope this helps. Cam