Written on September 17, 2012 at 7:50 pm

Since I had to search for this and hadn’t done it before, I figured I would blog it (need to start doing this more often) .

Anyway, I have a dynamic survey / question / answer scenario in one of our apps, so I needed to update a Rails attribute using a variable to retrieve it.

So here’s what I ended up doing:

def assign_item (object, attribute_name)
value = get_item_by_text(attribute_name.gsub(/_/, ' '))
unless value.nil?
object.send("#{attribute_name}=", value.answer_text)

Breaking this down, my value = get_item_by_text refers to another method that’s specific to my app, so just ignore that for your uses, but just assume that value is the result you want to use.

So as long as we have a value, we call ruby’s “send” method with our attribute_name and pass it our value.answer_text.

So if our attribute is first_name, this is the equivalent of calling object.first_name = value.

Hopefully this helps you.  I got this from this stackoverflow question.

If you have a safer / better way, please let me know in the comments.

No Comments

Category Code | Tags: , ,

Related Posts (automatically added):

Social Networks : Technorati, Stumble it!, Digg, de.licio.us, Google, Twitter, Yahoo, reddit, Blogmarks, Ma.gnolia.

You can follow any responses to this entry through the RSS 2.0 feed.

No Responses to “Dynamically updating a rails attribute”

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">

Inappropriate comments will be removed at admin's discretion.