Rails 3 controller - if question record doesn't have a corresponding answer record, create one
I've worked with rails 2... but i'm still a rails 3 noob/disaster.
@questions is a set of questions from the questions table. I need to make sure that each question has a corresponding answer record in the answers table. If one does not exist, i need to create one with the default value of zero. In my controller i have the following:
# create records for answers that do not exist yet
@questions.each do |q|
a = Answer.where(q.id = Answer.question_id and current_user.id = Answer.user_id )
if a.nil?
Answer.new(:question_id => q.id, :score => 0)
end
end
I am getting this error:
开发者_如何转开发undefined method `question_id'
I'm going on vacation and taking the 4th edition of Agile Web Development with Rails (don't tell my wife :=]) Any help you can offer here would help.
Thanks.
Your code should look like this
@questions.each do |q|
a = Answer.where(:question_id => q.id, :user_id => current_user.id)
if a.empty?
Answer.new(:question_id => q.id, :score => 0)
end
end
But it can be refactored as
@questions.each do |q|
q.answers.create(:score => 0) unless q.answers.where(:user => current_user).any?
end
EDIT
As far as you don't understand what is going on here: you should or create
or save
your object:
answer = Answer.new(:question_id => q.id, :score => 0)
answer.save
or
Answer.create(:question_id => q.id, :score => 0)
The activerecord query syntax is incorrect. It should be something like this -
@questions.each do |q|
a = Answer.where("question_id = ? AND user_id = ?", q.id, current_user.id )
if a.nil?
Answer.new(:question_id => q.id, :score => 0)
end
end
Look at this post for more details http://m.onkey.org/active-record-query-interface
assuming you have added a has_many
relationship to Question
, you could do this
@questions.each do |q|
if q.answers.empty?
q.answers.create! :score => 0, :user => current_user
end
end
It iterates over the questions, checks to see if the question has answers, and adds one with score zero and user current_user
, if it is empty. It also will raise an error if the save fails (that's what adding !
to create
or save
does).
You will have to ensure your models know about the relationships for this to work:
class Question < ActiveRecord::Base
has_many :answers
end
class Answer < ActiveRecord::Base
belongs_to :question
belongs_to :user
end
精彩评论