[Rails] Re: ActiveRecord design question

Jean-Daniel Beaubien jd at jackdan.net
Fri Jul 28 15:38:11 GMT 2006


Dr Nic wrote:
>> user = User.find(:first)
>> user.user_options[:key] => this would return :value
>>     
>
> Try:
>
> class User < AR::Base
>   has_many :user_options do
>     def [](*args)
>       ... search code goes here...
>     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 [](key)
      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







More information about the Rails mailing list