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(/_/, ' '))
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.
Related Posts (automatically added):
You can follow any responses to this entry through the RSS 2.0 feed.