Reputation: 35
I have a controller called employees.
class EmployeesController < ApplicationController
def admission
@bank_fields = BankField.all.where(:status => true)
if @bank_fields.empty?
redirect_to :action => "show", :id => @bank_fields.first.id
end
end
def show
@employee = Employee.find(params[:id])
end
# The RESTful actions are as usual; I didn't give those here.
end
in the routes file
match ':controller/:action/:id', :via => [:get, :post,:put]
match ':controller/:action', :via => [:post, :get]
resources :employees
In the view I called the that admission action by
<%= link_to 'admission', :controller => :employees, :action => :admission %>
but when i press the link i got the following error.
ActiveRecord::RecordNotFound at /employees/admisson
Couldn't find Employee with id=admisson
That means its hitting to the show action.Which i dont know why.Is there any solution.Thanks
Upvotes: 0
Views: 134
Reputation: 76774
Your problem is you're not using Rails' resourceful routing structure (which is the basis of how Rails calculates Routes):
#config/routes.rb
resources :employees
#-> get /employees, to: "employees#index"
#-> get /employees/:id, to: "employees#show", id: :id
#-> get /employees/new, to: "employees#new"
#-> post /employees/new, to: "employees#create"
#-> get /employees/:id/edit, to: "employees#edit"
#-> patch /employees/:id, to: "employees#update"
#-> delete /employees/:id, to: "employees#destroy"
You can use the collection
method to give you "collective" routes (where collections of data are stored), or member
routes (where single data records are handled):
#config/routes.rb
resources :employees do
get :admission, as: :collection
end
This is compounded with your abstinence from the Rails path helpers, which will help you route your requests accordingly:
<%= link_to 'admission', employees_admission_path %>
Upvotes: 0
Reputation: 33542
As per the comments,if you want to redirect to the match ':controller/:action', :via => [:post, :get]
,just edit your routes as below.
match ':controller/:action', :via => [:post, :get] #primary
match ':controller/:action/:id', :via => [:get, :post,:put] #secondary
Before you have
match ':controller/:action/:id', :via => [:get, :post,:put] #primary
match ':controller/:action', :via => [:post, :get] #secondary
So,the primary route demands an :id
and you are not passing an :id
in your link_to
. So is the error.
Upvotes: 0
Reputation: 5558
The routes in your route.rb file are a bit odd. Just use the generic way of specifying a custom action by adding it to the resources block:
resources :employees do
collection do
get :admission
end
end
Upvotes: 1