【问题标题】:Using helper class for boolean button为布尔按钮使用帮助类
【发布时间】:2018-05-08 11:29:17
【问题描述】:

我的按钮如下

<% if user.active == true  %>
        <%= button_to "Block", user_path(id: user.id, active: false), class: 'btn btn-outline-dark',  method:  :patch %>
        <%else%>
        <%= button_to "Unblock", user_path(id: user.id, active: true), class: 'btn btn-outline-dark',  method: :patch %>
        <%end%>

我需要为上面的视图代码创建辅助类,而不是重复按钮两次。谁能帮帮我

【问题讨论】:

    标签: ruby-on-rails ruby button boolean helper


    【解决方案1】:

    或者你可以只提供button_to helper 内部的逻辑:

    <%= button_to (user.active ? "Block" : "Unblock"), user_path(id: user.id, active: !user.active), class: 'btn btn-outline-dark',  method:  :patch %>
    

    因此,如果您仍然认为它很冗长,您可以将(user.active ? "Block" : "Unblock") 逻辑移动到装饰器的助手中。

    【讨论】:

      【解决方案2】:

      在助手中:

      def block_button(is_active)
        button_to is_active ? 'Block' : 'Unblock', user_path(id: user.id, active: !is_active), class: 'btn btn-outline-dark',  method:  :patch
      end
      

      在模板中

      <%= block_button(user.active) %>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-11-27
        • 2017-07-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-04
        • 1970-01-01
        相关资源
        最近更新 更多