[Rails] ActiveRecord design question

Jean-Daniel Beaubien jd at jackdan.net
Fri Jul 28 02:19:59 GMT 2006


Hi everyone, I have a small design question.

My app has the classical 'User' table.  The problem is that I will 
probably have a lot of user set options.  I did not want to add 20-30 
fields to the user table so I created a user_options table:

===============================
class User < ActiveRecord::Base
  has_many :user_options
end
===============================
class UserOption < ActiveRecord::Base
  belongs_to :user
end
===============================

Unfortunately this does not give me what I want.  My problem is the 
following:  I would like to be able to reference the user_options like 
this: 

user = User.find(:first)
user.user_options[:key] => this would return :value

But unfortunately the way I did it does not work like this.  I have to 
go through the user.user_options array and find the proper key and I 
cannot figure out how to accomplish this...

Any idea how I could do this?

Thank you in advance,

Jd

P.S.  Would there also be a simple rails way to verify that there is 
indeed a value set for the given :key, and if not give it a default 
value?  I've been trying to make this work,but I'm still very new to rails.






More information about the Rails mailing list