Should proxy_owner be eager loaded?

I'm running into an issue where I'm defining an association extension:

class User < ActiveRecord::Base

has_many :credentials do   def update(key,val)     cr = proxy_target.select{ |c| c.id == key.to_i}.first     cr.update_attributes(val) unless cr.nil?   end end

This code fails, because proxy_target == , unless the association has been loaded already, i.e. someone called user.credentials prior to this.

In activerecord-2.0.2/active_record/associations/association_proxy.rb, there is

def proxy_target         @target end

I wonder if this should be

def proxy_target         load_target         @target end

Thanks,

Wolf

class User < ActiveRecord::Base

has_many :credentials do

def update(key,val)

cr = proxy_target.select{ |c| [c.id](http://c.id) == key.to_i}.first

cr.update_attributes(val) unless cr.nil?

end

end

You don’t need to call proxy_target yourself. The association proxy is built to allow you to treat it like it was the target. So the following should load the target and do what you want:

def update(key,val) cr = detect { |c| c.id == key.to_i} cr.update_attributes(val) unless cr.nil? end

Although you could probably find an easier way to update a record in the association.

::Jack Danger

Thanks, that worked.

The reason I'm updating attributes in this "complicated" way is that I've overridden the credentials= assign method, so that I can handle CUD (create, update, delete) operations on the association from the same form w/o special-casing in the controller. The controller just calls

@user.attributes = params[:user] @user.save!

rescue ...

Thanks,

Wolf