我有一个答案模型,它有一个“正确”的布尔列,就像 stackoverflow 一样,答案可以被标记为正确。我有以下使用切换的控制器代码!切换“正确”布尔值的方法,但是,切换!跳过我想避免的所有验证。
如何修改我的代码以避免使用切换!在控制器中允许验证并仍然使用单个按钮来切换布尔值?
路线.rb
resources :answers do
member { put :correct }
end
correct_answer PUT /answers/:id/correct(.:format) answers#correct
answers_controller.rb
def correct
@answer = Answer.find(params[:id])
if @answer.toggle!(:correct)
respond_to do |format|
format.html { redirect_to @answer, notice: "Submitted" }
format.js
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>