ruby on rails - Proper way to write a value for an attribute whose name is in a variable? -


lots of searching here , around suggested use second argument send() write value attribute, in rails 4 told have wrong number of parameters:

> prj = project.where(:id => 123).first > fieldname = "project_start_date" > prj.send(fieldname, date.today) argumenterror : wrong number of arguments (1 0) 

that approach thought synonymous with

> prj.write_attribute(fieldname, date.today) 

but errors

nomethoderror : private method `write_attribute' 

which odd since docs part of instance public methods.

the activerecord docs suggest using class update method:

# updates 1 record person.update(15, user_name: 'samuel', group: 'expert')  # updates multiple records people = { 1 => { "first_name" => "david" }, 2 => { "first_name" => "jeremy" } } person.update(people.keys, people.values) what's rails 4 guy supposed do? 

in case translate to:

project.update(123, project_start_date: '2013/09/04') #not using variables testing sake 

and yields me nice:

 activerecord::statementinvalid: pg::syntaxerror: error:  zero-length delimited identifier @ or near """" line 1: ...dual".* "project"  "project"."" = $1 li... 

so what's rails 4 user supposed use, other writing out actual sql statements?

you're close in first example. reason send isn't working because you're trying do:

prj.project_start_date(date.today) 

which doesn't make sense because project_start_date method not take argument. need change setter

prj.project_start_date = date.today 

which translate to:

prj.send("#{fieldname}=", date.today) 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -