Eval on LHS of Assignment

I want to set the values of several record fields from within an
iterator where the field name is passed as a parameter. For example
(conceptually):

# Line numbers are for reference only and are not a part of the code.
1. record=Model.find(id)
2. params.each do |key,value|
3. eval('record.'+key)=value
4. end

Apparently, having the eval on the LHS of an assignment doesn't work.
Can anyone please tell me what would work?

Thanks for any input.

         ... doug

Doug Jolley wrote:

I want to set the values of several record fields from within an
iterator where the field name is passed as a parameter. For example
(conceptually):

# Line numbers are for reference only and are not a part of the code.
1. record=Model.find(id)
2. params.each do |key,value|
3. eval('record.'+key)=value
4. end

Apparently, having the eval on the LHS of an assignment doesn't work.
Can anyone please tell me what would work?

record[key] = value

Note that this relies on the hash-like behavior of ActiveRecord. If you
wanted to do this with a non-AR object, you could use
record.send("#{key}=", value). eval is rarely necessary in Ruby.

However, in this case, you could just do
record.update_attributes(params).

Thanks for any input.

         ... doug

--

Best,

First of all if you are doing this from a controller, you probably
don't want to use ALL of the parameters, but only those for the model,
probably coming from a form,

For an active record model you can do:

# Assuming that the model really is called Model, and you are
following Rails conventions for the form:
model_params = params[:model] || []

model_params.each do |key, value|
   record[key] = value
end

or just

record.attributes=(model_params, false)

The false overrides the protection of attributes, and probably isn't a
good idea in general. You normally don't want to blindly mass assign
any attributes the user throws at you. Consider the fact that the
incoming url might be coming from a form submission from your app, or
might be forged.

Wow, two really thorough answers. Thanks so much. Sorry for the
delay in responding. I wanted to see if I couldn't get this thing
working before responding; but, alas, I ran into other problems.
However, I would have to say that this issue has definitely been put
to bed. Thanks for the input.

Oh, BTW:

# Assuming that the model really is called Model,

It isn't. I chose that name for illustrative purposes.

Thanks to all for the input.

       ... doug