I’m using a custom action to get the id of a project into the session, so that only relevant info for that project is shown in other areas. I’ve made a custom action in the projects controller, and am having trouble getting a link to work in the view to call that action. I just get an error saying “Couldn’t find project without ID”. I’m new to rails – I know it’s probably an easy question, but help would be much appreciated, thanks!
View Code:
<%= link_to 'Select Project', :action => :select_project %>
Controller Code:
def select_project
@project = Project.find(params[:id])
session[:project_id] = @project.id
end
Routes:
resources :projects do
collection do
get :select_project
end
end
Alternative routes code:
resources :projects do
put 'select_project', on: :member
end
This is untested but I believe it is what you are looking for:
Routes:
this should create the following:
Controller
Views
See:
Note also the use of ‘post’ instead of ‘get’, since we are changing the state of an object (session)
it is preferred to use a post not a get, otherwise users might pull up an old get request in the address bar
of their browser and set their session to a project unknowingly.
like
varatissaid – userake routesorCONTROLLER=projects rake routesto help with determining what your route/path helpers look like and what http verbs they are expectingThe @project creates an instance variable; in a rails controller instance variables are made available to the views. This set_current action will never render a view, so no reason to make an instance variable out of it.
any action where you want to reference
params[:id]should be a member route, an alternative would be to leave it as a collection route and passparams[:project_id]and pass that in all of your link_to calls, but in this case member makes more sense.I believe
resources :projectsis a short cut for this break downhopefully that clarifies your questions some?