2013-07-14 107 views
0

我有rails_best_practices寶石和我得到以下警告:Ruby on Rails的使用模特協會

APP/app/controllers/users_controller.rb - use model association (for @user_answer)

參考這個要點的代碼:

begin 
    @user_answer = @user.user_answers.where(:question_id => @question_id).first 
    if @user_answer 
    @user_answer.answer_id = @answer_id 
    @user_answer.save! 
    @message = 'Answer updated successfully!' 
    else 
    @user.user_answers.create(:question_id => params[:questionId], :answer_id => params[:answerId]) 
    @message = 'Answer submitted successfully!' 
    end 
rescue ex 
    @message = ex.message.split(':')[1].chomp 
end 

但根據page on model association它看起來不像是違反了這一點,它看起來像是正確的。我是否錯過了這件事?

+0

哪一行是第33行?我認爲這是抱怨「@ user_answer.answer_id = @answer_id」,它看起來像在你分享的鏈接中解釋的氣味類似 –

+0

哎呦我刪除了指向代碼所在的方法的行號(所以行號實際上並沒有幫助解決這個問題) – acconrad

回答

1

問題在於直接訪問變量在@user_answer對象,並且@user變量中不更新user_answer ...既然Rails有一個update方法,我們可以做到這一點,像這樣:

begin 
    @user_answer = @user.user_answers.where(:question_id => @question_id).first 
    if @user_answer 
    @user.user_answers.update(:question_id => @question_id, :answer_id => @answer_id) 
    @message = 'Answer updated successfully!' 
    else 
    @user.user_answers.create(:question_id => @question_id, :answer_id => @answer_id) 
    @message = 'Answer submitted successfully!' 
    end 
rescue ex 
    @message = ex.message.split(':')[1].chomp 
end 

但我們可以做得更好。與創建和更新不同,我們可以簡單地使用Ruby的短路評估來創建@user_answer符號並更新它,無論它是否是新的。

begin 
    @user_answer = @user.user_answers.where(:question_id => @question_id).first || @user.user_answers.new 
    @user_answer.update_attributes!(question_id: @question_id, answer_id: @answer_id) 
    @message = 'Answer submitted successfully!' 
rescue ex 
    @message = ex.message.split(':')[1].chomp 
end