How to route to custom controller action in Rails 3?

I am new to Rails and am 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 would like to access the custom_action action via the url:

http://foo.bar/devices/custom_action

I added this line to the routes.rb file:

match 'devices/custom_action' => 'devices#custom_action'

However, when I try to use 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 a #show action instead of #custom_action. If the user id is not specified and I go to http://foo.bar/devices/custom_action, I would like it to perform #custom_action.

I read Rails Routing from the Outside , but still cannot figure out how to solve this.

+3
source share
1 answer

, - , .

, resources :devices routes.rb. , , . rake routes /, , :

GET     /devices/:id

resources :devices, . Edge Guides, , 1.1. URL- , , . resources :devices.

+3

Source: https://habr.com/ru/post/1774635/


All Articles