【问题标题】:Toggle rails boolean using link_to with validations使用带有验证的 link_to 切换 rails boolean
【发布时间】:2013-06-03 10:42:26
【问题描述】:

我有一个答案模型,它有一个“正确”的布尔列,就像 stackoverflow 一样,答案可以被标记为正确。我有以下使用切换的控制器代码!切换“正确”布尔值的方法,但是,切换!跳过所有我想避免的验证。

如何修改我的代码以避免使用切换!在控制器中以允许验证并仍然使用单个按钮来切换布尔值?

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>

【问题讨论】:

    标签: ruby-on-rails ruby routes boolean


    【解决方案1】:

    source code 节目

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2017-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多