【问题标题】:Ruby On Rails - Button run functionRuby On Rails - 按钮运行功能
【发布时间】:2019-08-18 19:14:51
【问题描述】:

好的,所以我对 ruby​​ on rails 有点陌生。当我按下按钮时,我试图调用一个函数。但我不知道该怎么做。

这基本上是我想要做的:

<% button_to 'Ban User', call_this_function %>

<% this_function %>
 @user = User.find(:id)
 @user.deactivated("true")
<% end %>

这是我写的一些实际代码

  <% if has_role?(:admin) %>
    <% if !@user.deactivated %>
      <% if !@user.has_role?(:admin) %>
        <%= link_to 'Ban User', new_discussion_path, class:"button is-danger" %>
      <% end %>
    <% else %>
      <%= link_to 'Unban User', new_discussion_path, class:"button is-success" %>
    <% end %>
  <% end %>

但这只会重定向到我可以创建新讨论的页面。我想要做的是在按下按钮时调用一个命名函数,但不要重定向到其他页面。很抱歉缺少代码,但请询问您是否需要澄清。

【问题讨论】:

  • 看起来getting started 可能会对您有所帮助。基本上你需要生成模型、控制器和视图。 Example updating articles 可能与您的情况很接近,因为您可以使用 @user.deactivated("true") 更新 User

标签: html ruby-on-rails function button


【解决方案1】:

将控制器操作添加到相应的控制器,例如,

def ban_user
 @user = User.find(params[:id])
 @user.deactivated("true")
end

将此操作添加到您的 routes.rb

get 'controller/ban_user'

现在您可以将链接添加到您的视图中

<%= link_to 'Ban User', controller_user_ban_path(:id => @user.id), class:"button is-danger", remote: true %>

这将在不加载页面的情况下调用该函数。

【讨论】:

    猜你喜欢
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多