krs8888
krs8888

Reputation: 1349

Calling a method from button and passing parameters to in Ruby rail

I am new to ruby and one of the things on my page I am trying to do is take input from user and on button click want to make a call to the method for processing.

The controller looks like

def index
  //code
end

def create
 //code
end

def doSomeAction
 //This is where I want to process
end

This is the view

<%= form_tag(project_path, multipart: true, class: 'form-inline', role: 'form') do %>

  <%= button_tag 'upload batch file', class: 'btn btn-primary' %>
  <%= link_to 'Reports Index', reports_path %>

<% end %>

<%= text_field "item", "ids", "size" => 20 %>
<%= button_to 'Call Action', method: "doActionTest" %>

This is the routes

Rails.application.routes.draw do     

  resources :browse_items, only: [:index, :show]
  resources :reports, only: [:index, :show]

  resources :project, only: [:index, :create, :show]
  root to: "project#index"
end

How to map the button to doActionTest and how to pass value from the text field to that method ?

Upvotes: 0

Views: 961

Answers (1)

bkunzi01
bkunzi01

Reputation: 4561

You need to setup a route pointing at that action inside that controller.

In your config/routes.rb file you should add

post 'doSomeAction', to: 'ControllerNameHere#doSomeAction', as: 'do_some_action'

Then in your form_tag you want to change the url its pointing to from 'project_path' to: do_some_action_path

Then change the button you have to: <%= button_to 'Call Action', method: :post %>

The method they want explicitly stated is the HTTP request (like get, put, post, etc) and not the action in your controller.

As a sidenote, your action name shouldn't be camelcased but instead separated by underscores if you want to follow ruby best practices you should make the action name do_some_action (if you do that make sure you change the routes accordingly)

Upvotes: 2

Related Questions