ruby-on-rails

Rails: How to use own actions in view

Follow me
Follow me

Latest posts by Tomasz Antas (see all)

Dec 20, 2014

Ruby on Rails framework provides using actions such as index, new and update by default. In this short article we show how to use own actions.

CONTROLLER:

Let’s assume we have a following controller for project model:

project_controller.rb

In the controller above, an own action called mymethod is added, which will be later used in show view. Let’s assume that the mymethod will operate on particular project, so we need its id.

 

ROUTING

We need add the route for our mymethod. Open config/routes.rb and type:

(If you have added: resources :projects, to routes.rb, remove it). After all, the routes.rb should look like this:

Launch terminal and execute:

Displayed text should contain something similar to the following line:

You can open also: “localhost:3000/routes” in your web browser. You should get a list of already created routes and find there:

mymethod_projects_path is a link to our action, which we will use in show view.

 

VIEW

We use the link_to element to invoke our action.

projects/index.html.erb:

As you can see, we used mymethod_projects_path as a link to our action and we have passed an id of our project.

Tomasz AntasRails: How to use own actions in view