ActiveRecord design question

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.

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

Try:

class User < AR::Base
has_many :user_options do
def
… search code goes here…
end
end
end

Dr Nic wrote:

end

end
end

This is very neat I had no idea you would do this…However seem I’m
too much of a newbie to figure it out completely on my own.

Now using your snippet of code, my search code is, in effect, in the
user_options class. What am I trying to do is reach the
user.user_options array and search through it with something like
user_options.find {|opt| opt.key==key}. Unfortunately I can’t manage to
reach the user_options array, since I am in the user_options class. And
since the user_options class doesn’t inherit from User, I can’t use
‘super’.

I guess I could query the database, but I taught it would be simpler and
more DRY to reuse the user.user_options array, since I wouldn’t have to
deal with the database at all like this. (And I could also use another
method like def[]=(*args) to put values back in the user_options without
dealing directly with the db).

Any help would be greatly appreciated.

Here a non-working example of what i’m trying to do (I just improvised
the def []= so it could veyr well not work the way it’s written atm):

class User < AR::Base
has_many :user_options do
def
return super.user_options.find {|opt| opt.key==key}
end

def []=(key, value)
super.user_options.each do |opt|
    if opt.key==key
	opt.value=value
    end
end
end

end

end