如何在Rails 3中创建自定义控制器操作的路由?

时间:2010-11-13 00:19:06

标签: ruby-on-rails-3 routing controller

我是Rails的新手,对路线有点困惑:

我有一个设备控制器:

#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

我想通过以下网址访问“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动作而不是#custom_action。如果没有提供用户ID,我转到http://foo.bar/devices/custom_action,我希望它去#custom_action。

我已阅读Rails Routing from the Outside,但似乎仍无法解决问题。

1 个答案:

答案 0 :(得分:3)

我认为问题可能是由于您定义路线的顺序。

我怀疑你resources :devices中有routes.rb。此外,我怀疑您已经在之后定义了自定义路线。如果在控制台/终端中键入rake routes,您将看到已经为以下模式定义了路由:

GET     /devices/:id

此路线是resources :devices的乘积,优先于您的自定义路线。返回参考Edge Guides,特别是在1.1. Connecting URLs to Code中,它指出请求将被分派到 第一个 匹配路由。因此,一个简单的解决方法是在resources :devices之前定义自定义路由。