I'm new to Rails, and a bit confused about routes:
I have a Devices controller:
#devices_controllers.rb
class DevicesController < ApplicationController
def index
@devices = Device.all
end
def show
@device = Device.find(params[:id])
end
def new
@device = Device.new
end
def create
@device = Device.new(params[:device])
if @device.save
flash[:notice] = "Successfully created device."
redirect_to @device
else
render :action => 'new'
end
end
def edit
@device = Device.find(params[:id])
end
def update
@device = Device.find(params[:id])
if @device.update_attributes(params[:device])
flash[:notice] = "Successfully updated device."
redirect_to @device
else
render :action => 'edit'
end
end
def destroy
@device = Device.find(params[:id])
@device.destroy
flash[:notice] = "Successfully destroyed device."
redirect_to devices_url
end
def custom_action
"Success"
end
I'd like to access the "custom_ac开发者_运维百科tion" action via a url like this:
http://foo.bar/devices/custom_action
I've added this line to my routes.rb file:
match 'devices/custom_action' => 'devices#custom_action'
However, when I try the URL in the browser, I get this error:
ActiveRecord::RecordNotFound in DevicesController#show
Couldn't find Device with ID=custom_action
It seems to be going to #show action instead of #custom_action. If a user id is not supplied, and I go to http://foo.bar/devices/custom_action
, I'd like it to go #custom_action.
I've read Rails Routing from the Outside, but still can't still seem to figure out the problem.
I think the problem may be because of the order in which you have defined your routes.
I suspect you have resources :devices
in your routes.rb
. In addition, I suspect you have defined your custom route after this. If you type rake routes
into your console/terminal, you will see that there is already a route defined for the following pattern:
GET /devices/:id
This route is a product of resources :devices
, which is taking precedence over your custom route. Referring back to the Edge Guides, specifically in 1.1. Connecting URLs to Code, it states that the request will be dispatched to the first matching route. So a simple fix would be to define your custom route before resources :devices
.
精彩评论