Accessing model attribute name dynamically

I’m calling this action from within another action:

edit_meta(@table_meta_id, @field, @content)

where @field is an attribute name for a Model. @table_meta_id is the id
and @content is the new value for that attribute.

The edit_meta action looks like this:

def edit_meta(id, field, content)

@meta = Model.find(:all, :conditions => ["id = ?", id])
@meta.field = content
@meta.updated_at = now()
@meta.save

end

Problem is that I can’t figure out how to get the field argument to tell
my model which attribute I want to change. I just get a “NoMethodError”.
How do I do that?

Thanks!

How about:

@meta.send("#{field}=", content)

Jamey

On Fri, Jul 10, 2009 at 4:31 PM, Dan

Jamey C. wrote:

How about:

@meta.send("#{field}=", content)

Jamey

On Fri, Jul 10, 2009 at 4:31 PM, Dan

That’s it. Thanks!

Another alternative:


@meta[field] = content

Jeff

On Jul 13, 9:32 am, Dan B. [email protected]

Jeff B.systems wrote:

Another alternative:


@meta[field] = content

Jeff

On Jul 13, 9:32�am, Dan B. [email protected]

I tried that one, and it didn’t work … error message said Ruby
couldn’t translate {field} into an integer, even though I wanted a
string… But thanks.

Maybe I’m not understanding what you’re sending as a val for @field,
because if it’s a string of the model attribute name, it should work:

$ script/console

klass = Klass.find(:first)
=> #<Klass …>

klass.foo
=> “bar”

klass[“foo”]
=> “bar”

klass[“foo”] = “biz”
=> “biz”

klass[“foo”]
=> “biz”

klass.foo
=> “biz”

Jeff

On Jul 13, 9:58 am, Dan B. [email protected]