我有一个答案模型,它属于具有“正确”布尔列的问题。理想情况下,一个问题只能有 1 个正确答案(很像 stackoverflow 系统)。
我有以下控制器+模型代码,它使用一种toggle_correct
方法来切换视图中的“正确”布尔值(所有这些都很好)。
当我尝试创建新答案时,one_correct_answer
即使正确的列设置为默认值,也会引发验证错误:迁移中的 false 并且应用程序 POST 跟踪中的值设置为 0 (false)
如何修改我的代码,以便此验证仅允许每个问题有 1 个正确答案,并且不会中断新答案对象的创建?
答案.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
answers_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>