2013-06-03 3 views
1

"올바른"부울 열이있는 응답 모델이 있습니다. 따라서 stackoverflow와 마찬가지로 답변을 올바른 것으로 표시 할 수 있습니다. 토글을 사용하는 다음 컨트롤러 코드가 있습니다! 메서드를 사용하여 "올바른"부울 값을 토글합니다. 모든 검증을 건너 뜁니다.유효성 검사를 사용하여 link_to를 사용하여 레일 부울 토글 전환

토글을 사용하지 않도록 내 코드를 어떻게 수정할 수 있습니까? 컨트롤러에서 유효성 검사를 허용하고 여전히 단일 버튼을 사용하여 부울 값을 전환 할 수 있습니까?

routes.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> 

답변

2

source code

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

그리고 update_attribute은 유효성 검사를 실행하지 않습니다. save(false).

유효성 검사를 실행하는 update_attributes을 사용하여 재정의 할 수 있습니다.
이와 비슷한

def toggle!(attribute) 
    toggle(attribute).update_attributes({attribute => self[attribute]}) 
end 
관련 문제