「正しい」ブール列を持つ質問に属する回答モデルがあります。理想的には、質問の正解は 1 つだけです (stackoverflow システムによく似ています)。
ビューで「正しい」ブール値を切り替えるメソッドを使用する次のコントローラー+モデルコードがありtoggle_correct
ます(すべてうまく機能します)。
新しい回答を作成しようとするとone_correct_answer
、正しい列がデフォルトに設定されていても検証エラーが発生します: 移行で false に設定され、アプリケーション POST トレースで値が 0 (false) に設定されます
この検証で問題ごとに 1 つの正解のみが許可され、新しい回答オブジェクトの作成が中断されないように、コードを修正するにはどうすればよいですか?
answer.rb
validate :one_correct_answer
def one_correct_answer
answers = self.question.answers.map(&:correct)
errors.add(:user_id, "You can't have more than 1 correct answer #{answers}") if answers & [true]
logger.debug("Answers array #{answers}")
end
def toggle_correct(attribute)
toggle(attribute).update_attributes({attribute => self[attribute]})
end
answer_controller.rb
def correct
@answer = Answer.find(params[:id])
if @answer.toggle_correct(:correct)
respond_to do |format|
format.html { redirect_to :back, notice: "Answer submitted" }
format.js
end
end
end
_answer.html.erb
<div id="correct_answer_<%= answer.id %>" class="<%= answer.correct == true ? 'green-tick' : 'default-tick' %>">
<% if answer.question.user == current_user %>
<%= link_to "✓", correct_answer_path(answer), id: "tick", class: "correct_#{answer.id}", remote: true, method: :put %>
<% else %>
<% if answer.correct == true %>
<div id="tick", class='correct_<% answer.id %>'> ✓</div>
<% end %>
<% end %>
</div>