Reputation: 2464
Why does update attribute not work here? If it shouldn't be used at the model level, then what could I use instead to accomplish what I'm trying to accomplish below?
class Question < ActiveRecord::Base
attr_accessible :body, :title
def getNewTitle qid
if qid.is_a? Integer
"new question title"
end
end
# should only have to run it once
def updateTitles
Question.all.each do |q|
begin
newTitle = getNewTitle q.id
if newTitle
q = Question.find(q.id)
q.update_attribute(:title => newTitle)
end
rescue
puts "======================error======================"
end
end
end
end
Upvotes: 0
Views: 86
Reputation: 8526
As Vimsha noted, update_attribute
takes two arguments.
But at the risk of being voted down, I would offer an alternative-- use update
. update_attribute
bypasses validation, using update
will ensure that your changes pass validation before saving.
For example:
Question.all.each do |q|
begin
newTitle = getNewTitle q.id
if newTitle
Question.update(q.id, title: newTitle)
end
rescue
puts "======================error======================"
end
end
API references
for update
and update_attribute
Upvotes: 0
Reputation: 29349
update_attribute
takes in two arguments. attribute name and value
q.update_attribute(:title, newTitle)
What you have is the syntax for update_attributes
q.update_attributes(:title => newTitle)
rails convention is to use underscores instead of camelCase for method names and variable names
Eg, new_title, update_titles
Upvotes: 3