How to change dynamic model field using Rails parameter?

I have a question about Ruby on Rails models:

I have this method in Rails that gets the column name and a new value for this 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 generates an error: this field does not exist, I think it should be something like: name ,: lastname, etc.

How can I convert a field variable to one of them dynamically so that this function works?

+3
source share
1 answer

You should check if the name of the field you get in params[:field]is exactly the same as the name of the original field (without extra spaces, etc.). You can check it on puts params[:field].inspectand check it on the terminal (where the rails server is running).

update_attribute . , update_attribute. , :

def update_attribute(name, value)
  name = name.to_s
  raise ActiveRecordError, "#{name} is marked as readonly" if self.class.readonly_attributes.include?(name)
  send("#{name}=", value)
  save(:validate => false)
end

, . @jdoe, (. save(:validate => false) ), , .

+2

All Articles