[Rails] Dealing with attributes in join tables

Gavin Sinclair gsinclair at soyabean.com.au
Wed Nov 24 06:15:14 GMT 2004


OK, so I have

  class User < ActiveRecord::Base
    has_and_belongs_to_many :games, :join_table => 'users_games'
  end

and I can do

  user = User.find(1)
  user.games                      # Works.
  user.games[0].is_for_trade      # There's an is_for_trade attribute
                                  #   in the join table.

So far so good.  But this is interesting:

  user.games[0].class             # -> Game

I guess it's not surprising that the user's game is a Game object, but
that Game object has an attribute that's not found in the 'games'
table; it's in the 'users_games' table.

My problem here is that I want to write a method #trade?, which
returns true or false, based on the value of 'is_for_trade', which
should be 0 or 1.

In which class is it most appropriate to create this method?  Game
comes to mind:

  class Game < ActiveRecord::Base
    has_and_belongs_to_many :users, :join_table => 'users_games'

    def trade?
      val = self.is_for_trade
      not (val.nil? or val == 0 or val == '0')
    end
  end

Putting it in Game has two drawbacks:

 * It's a method that can not be called on all Game objects,
   as not all Game objects have the 'is_for_trade' attribute.

 * Some User objects will also have the 'is_for_trade' attribute
   and might benefit from the #trade? method.  E.g.
   Game.find(1).users[0] will be a User object and will have
   'is_for_trade'.

Does anyone have any insights?

Thanks,
Gavin



More information about the Rails mailing list