Home > Net >  How to call this route un Ruby on rails
How to call this route un Ruby on rails

Time:04-17

I Made a scaffold and Made the class "project". This make in routes.rb the resources. I make another route

Get 'projects/status/:id', to 'projects#status'

How can i call this link on the HTML code? I tried

<%= link_to "show status", '/status'project.id %>

But it doesn't work. Please help

CodePudding user response:

To link to the path you defined use plain string with interpolation for :id parameter

# GET /projects/status/:id

# config/routes.rb
get 'projects/status/:id', to: 'projects#status'

# view
<%= link_to 'status', "/projects/status/#{@project.id}" %>

You can add a path helper method by using :as option. It is also better to append status path to keep it consistent with rails conventions and to not clash with :id param. This is similar to other project routes, like edit and new. Now you have status route for your project.

# project_status GET /projects/:id/status

# config/routes.rb
# NOTE: `as: :project_status` will create `project_status_path` and `project_status_url` helpers
get 'projects/:id/status', to: 'projects#status', as: :project_status

# view
# NOTE: path helper will automatically extract `:id` param from @project
<%= link_to 'status', project_status_path(@project) %>

Route can be nested under project resources. For all options see: https://api.rubyonrails.org/v7.0.2.3/classes/ActionDispatch/Routing/Mapper/Base.html#method-i-match

# status_project GET /projects/:id/status

# config/routes.rb
resources :projects do
  get :status, on: :member
end

# view
<%= link_to 'status', status_project_path(@project) %>

# TODO: maybe fix backwards helper name
# get :status, on: :member, as: :state_of
# => state_of_project_path(@project)

To see your routes

bin/rails routes
# helper name         # url                              # controller#action
project_status GET    /projects/:id/status(.:format)     projects#status
  • Related