Rails: add an action to a controller

I am creating an app with users. My UsersController has a show method. Thus, user with id = 1 can be reached at /users/1.

My routes.rb file contains :users resources. Thus, /users/1/edit renders the edit page for user with id = 1.

What I am trying to accomplish is creating a new action, which allows one to put a request for any user by reaching /users/USER_ID/request.

How do I do that? Appreciate the help in advance!

Upvotes: 1

Views: 1361

Answers (2)

Alexander Komarov
Alexander Komarov

Reputation: 182

First, create a following route (routes.rb):

get '/users/:id/request' => 'users#request', as: :user_request

Second, add a request method to UsersController:

def request
  @user = User.find params[:id]
  # do your thing
end

You can create a link to this URL in your views like so: <%= link_to 'Request', user_request_path(@user.id) %>

Upvotes: 2

Anthony E
Anthony E

Reputation: 11245

Not sure what you mean "controller within a controller". The above request should be possible by passing a block to your resources route.

However, it's very dangerous to use "request" as an action name since request is a commonly used method in action controller:

routes.rb

resources :users do
   put :process_request, on: :member
end

Users Controller:

def process_request
   # ...
end

Upvotes: 1

Related Questions