2

代码有异味,我确定我缺少一个帮手来进行简单的更新或创建如下代码段的查询:

  @user_answer = current_user.user_answers.find_by_question_id(params[:a_question])
  if @user_answer.nil?
    @user_answer = current_user.user_answers.build({ :answer_id => params[:an_answer] , :question_id => params[:a_question] })      
    @user_answer.save  
  else
    @user_answer.update_attributes(:answer_id => params[:an_answer])
    @user_answer.save 
  end
4

2 回答 2

4

您可能正在寻找find_or_initialize_by方法。例如:

@user_answer = current_user.user_answers.find_or_initialize_by_question_id(params[:a_question])
@user_answer.answer_id = params[:an_answer]
@user_answer.save
于 2012-11-01T03:15:19.407 回答
0

怎么样,

@user_answer = current_user.user_answers.find_or_create_by_question_id(params[:a_question])

这将避免显式保存

于 2012-11-01T04:15:25.180 回答