bigtunacan
bigtunacan

Reputation: 4996

ActiveRecord how to set associated attributes from a hash?

I have an ActiveRecord model instance where I want to modify attributes where some attributes exist on an association rather than directly on the model itself. All of the attributes come in as a hash.

This code is part of my test suite so I'm not concerned about issues of mass attribute assignment in this case.

If I try to update using instance.update_attributes(hash) this fails.

As an alternative I tried looping over the hash and setting the attributes like this.

hash.each do |key, val|
  instance[key] = val
end

This method will set attributes that exist directly on the instance, but throws an exception on attributes that are tied to associated records ActiveModel::MissingAttributeError Exception: can't write unknown attribute 'foo'

Upvotes: 0

Views: 528

Answers (1)

jvillian
jvillian

Reputation: 20253

Give the delegate approach a go. Something along the lines of:

  class Foo
    attr_accessor :bar, :foo_attribute
    delegate :bar_attribute=, to: :bar

    def initialize
      @bar = Bar.new
    end
  end

  class Bar
    attr_accessor :bar_attribute
  end

Then, in the console:

  hsh = {foo_attribute: 'foo', bar_attribute: 'bar'}
  f = Foo.new
  hsh.each do |k,v|
    f.send("#{k}=",v)
  end
  f.inspect
   => "#<Foo:0x00000004f1f0f0 @bar=#<Bar:0x00000004f1f0c8 @bar_attribute=\"bar\">, @foo_attribute=\"foo\">" 
  f.bar.inspect
   => "#<Bar:0x00000004f1f0c8 @bar_attribute=\"bar\">"

Upvotes: 1

Related Questions