我是 Rails 的新手,对路由有点困惑:
我有一个设备 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
我想通过这样的 url 访问“custom_action”操作:
http://foo.bar/devices/custom_action
我已将此行添加到我的 routes.rb 文件中:
match 'devices/custom_action' => 'devices#custom_action'
但是,当我在浏览器中尝试该 URL 时,出现了这个错误:
ActiveRecord::RecordNotFound in DevicesController#show
Couldn't find Device with ID=custom_action
似乎要#show action 而不是#custom_action。如果未提供用户 ID,我转到 http://foo.bar/devices/custom_action
,我希望它转到#custom_action。
我读过 Rails Routing from the Outside , 但似乎仍然无法找出问题所在。
最佳答案
我认为问题可能出在您定义路由的顺序上。
我怀疑您的 routes.rb
中有 resources :devices
。此外,我怀疑您在 之后 定义了您的自定义路线。如果您在控制台/终端中键入 rake routes
,您将看到已经为以下模式定义了一条路由:
GET /devices/:id
此路线是 resources :devices
的产物,它优先于您的自定义路线。引用边缘指南,特别是在 1.1. Connecting URLs to Code 中,它表明请求将被分派(dispatch)到第一个 匹配路由。因此,一个简单的解决方法是在 resources :devices
之前定义您的自定义路由。
关于ruby-on-rails-3 - 如何在 Rails 3 中创建一个自定义 Controller Action 的路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4170158/