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
on 2008-07-20 05:33
on 2008-07-20 08:10
On Sat, Jul 19, 2008 at 8:32 PM, Wolfram <wolfram@arnold.name> wrote: > > 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 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
on 2008-07-20 20:19
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 On Jul 19, 11:08 pm, "Jack Danger Canty" <dangeronra...@gmail.com>