简体   繁体   中英

Ruby On Rails - Button run function

Okey, so im kinda new to ruby on rails. Im trying to call a function when im pressing a button. But i have no idea how to do this.

This is basicaly what im trying to do:

<% button_to 'Ban User', call_this_function %>

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

Here is some actual code that I wrote

  <% 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 %>

But this only redirects to a page to where I can create a new discussion. What I'm trying to do is to just call a named function when impressing the button, but do not redirect to some other page. I'm sorry for the lack of code, but please ask if you need some clarification.

add a controller action to your corresponding controller like,

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

add this action to your routes.rb

get 'controller/ban_user'

now you can add the link to your views

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

this will call the function without loading the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM