In Rails how do I update form fields in the model?

Go To StackoverFlow.com

0

Let's pretend I want to set all the fields I specify to be = "frog"

In the model I can set each one manually using:

self.field1 = 'frog'
self.desc_field = 'frog'
self.fieldx = 'frog'
etc....

But how can I this by putting the field names in an array?

When I try

fields_array=['field1','desc_field','fieldx']    
fields_array.each { |field|    
  self.field = 'frog'
}        

It does not work. Any suggestions?

2009-06-16 09:40
by Datatec
What's the end result you're trying to achieve? You probably don't want this sort of code in a controller - John Topley 2009-06-16 09:50
Yes, Actually code is in model, thanks I updated the question. Actually wanting to clean out ms word unicode from form. Asked the question here stackoverflow.com/questions/998555/ But seems like people were overwhelmed by the full question, because no one answered. so thought someone might answer if it was in a simpler form - Datatec 2009-06-16 11:40


2

John Topley's answer above is basically correct, however since you want to assign values you want to doing something like:

fields_array=['field1','desc_field','fieldx']    
fields_array.each { |field|    
  self.send("#{field}=", 'frog')
}

Note the added equal sign. With that you're doing self.field1='frog' rather than self.field1('frog').

2009-06-16 11:47
by Jakob S
Good catch. I wasn't sure of the exact syntax for assignment and don't have a Ruby interpreter at hand - John Topley 2009-06-16 13:55


0

Try using the send method:

fields_array=['field1','desc_field','fieldx']    
fields_array.each { |field|    
  self.send("#{field}", 'frog')
}
2009-06-16 09:52
by John Topley
Action controller comes back with this error "wrong number of arguments (1 for 0) - Datatec 2009-06-16 11:34
Ads