Search code examples
ruby-on-railsactiverecordruby-on-rails-2

Assign Associated Record Without Eval (Rails 2.x)


My code looks like this

  #     record[field_name] = get_children(field_name)
  eval "record.#{field_name} = get_children(field_name)"

record is an ActiveRecord subclass, and the field in question is a has_a relationship. The commented line does not work (though it seems to, but the assign does not take place).

How can I do this without eval?


Solution

  • There may be a more Railsy way to do this, but at least you can eliminate the eval by using send (from Object), which all Object instances have:

    record.send "#{field_name}=", get_children(field_name)