1

我有一个答案模型,它有一个“正确”的布尔列,就像 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 %>'> ✓&lt;/div>
       <% end %>
    <% end %>
</div>
4

1 回答 1

2

代码显示

def toggle!(attribute)
  toggle(attribute).update_attribute(attribute, self[attribute])
end

并且update_attribute不运行验证,即。save(false).

update_attributes您可以使用which 运行验证来覆盖它。
像这样

def toggle!(attribute)
  toggle(attribute).update_attributes({attribute => self[attribute]})
end
于 2013-06-03T02:42:26.337 回答