john bowlee
john bowlee

Reputation: 185

Call an action on button click in ruby on rails

I have an action defined in my lib directory. The action is used to send a get request in the server. I want to execute the function on button click. How can I do this? I know this is not the right approach. I am new to rails.

show_document.rb (in lib directory)

class Legaldoc::ShowDocument

def view_document(sessionID, token_document)
    require 'rest-client'
    require 'zip'
    res = RestClient::Request.execute(
        :method => :get,
        :url => "http://myurl.com",
        :headers => {
            :ldsessionId => sessionID,
        }
    )
  end
end

in my view file

<%= link_to 'Button', '#', :onclick => "view_document(sessionID, token_document)" %>

Upvotes: 3

Views: 6582

Answers (1)

nathanvda
nathanvda

Reputation: 50057

I know this is confusing when you start developing in rails, but you have to consistently be very aware where your code is running. Your ruby code runs on the server, your html/js runs in the browser. Rails "prepares" html/js, but when you click a button, and you have to ask something from the server, you will have to use a url to acces a/any server.

Or you could resort to using javascript on the client directly, to fetch the data.

But since you already have the code in lib you will have to

  • add an endpoint, aka an action in a controller (add a new controller or add a new action in an existing controller, that is a bit hard with so little background information)
  • add a route to that controller/action
  • add the controller-code to call your lib function and format the answer in such a way relevant for the user

then add the button as follows:

 <%= link_to 'Button', my_action_controller_path(session_id: sessionId, token_document: token_document) %>

(the name of the path depends on the names of controller/action, and you can see the names of the routes by running rake routes)

However your code seems to just fetch a page at myurl.com, so you could also just build a link to myurl.com ?

<%= link_to 'Button', 'http://myurl.com', target: '_blank' %>

Upvotes: 5

Related Questions