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
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Gavin Sinclair wrote: | Does anyone have any insights? Active Record doesn''t pull the join table column types (yet) so it won''t typecast these attributes for you. Please post a trac ticket: http://dev.rubyonrails.org/trac.cgi/newticket Best, jeremy -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.6 (Darwin) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFBpC8dAQHALep9HFYRAjeKAKDaeco96n3vJF4DHV0CDifbjAZo1gCfbJkI dptf7S1BZrD84m3EVQn/v+M=MU5d -----END PGP SIGNATURE-----
On Wednesday, November 24, 2004, 5:50:06 PM, Jeremy wrote:> Gavin Sinclair wrote: > | Does anyone have any insights?> Active Record doesn''t pull the join table column types (yet) so it won''t > typecast these attributes for you. Please post a trac ticket: > http://dev.rubyonrails.org/trac.cgi/newticketI''m not sure what you''re getting at. It sounds like you''re answering my other question (the "MySQL adapter returns integers as strings?" thread). I guess if you or DHH confirm that, I''ll post a ticket. Anyway, my question in this thread relates to adding methods to an ActiveRecord-based model class. It''s easy for straightforward table-mapping classes. But for the results of a join, it''s not so clear to me. Thanks, Gavin