I have a question about models on Ruby on Rails:
I have this method on Rails that receives a name of the column and the new value for that column:
def change_attribute
field = params[:field]
new_value = params[:new_value]
person = Person.find(params[:id])
person.update_attribute(field, new_value)
render :text=>"", :layout=>false
end
But this throws me an error: that field doesn’t exist, I think it should be something like :name, :lastname, etc.
How can I convert my field variable into one of them dinamically to make this function work?
You should be checking whether the field name you get in
params[:field]is exactly the same as the original field name (no extra spaces etc.). You can check it byputs params[:field].inspectand checking it in the terminal (where the rails server is started).According to the docs for update_attribute, we will be able to pass string or symbol as the field name. So, you need not worry about converting the field parameter to symbol before passing it to
update_attribute. As you can see the source, here:It is first converted to string and then the setter is called. As @jdoe mentioned, it is not validating the model (see the
save(:validate => false)line in code), so you should be aware of that when you are using this method.