如何向路由添加其他资源操作?

时间:2013-10-17 11:42:09

标签: ruby-on-rails routing routes ruby-on-rails-4

我有一个名为志愿者的资源:

class VolunteersController < ApplicationController

  before_filter :authenticate_user!

  def index
    #@volunteers = Volunteer.all()
    @volunteers = Volunteer.paginate(:page => params[:page])
  end

  def show
    @volunteer = Volunteer.find(params[:id])
  end

  def new
    @volunteer = Volunteer.new
  end

  def create
    @post = Volunteer.new(volunteer_params)

    @post.save
    redirect_to @post
  end

  def destroy
    @volunteer = Volunteer.find(params[:id])
    @volunteer.destroy
    redirect_to :action => 'index'
  end

  def search
    @volunteers = Volunteer.search params[:search]
  end

private

  def volunteer_params
    params.require(:volunteer).permit(:forename, :surname)
  end

end

我添加了一个名为搜索的附加操作,但我在将其映射到路径文件中时遇到了问题:

root 'home#index'
resources :volunteers

如何映射到搜索操作(包括参数)?

1 个答案:

答案 0 :(得分:8)

路径文件本身有一个例子:

  # Example resource route with options:
  #   resources :products do
  #     member do
  #       get 'short'
  #       post 'toggle'
  #     end
  #
  #     collection do
  #       get 'sold'
  #     end
  #   end

您需要将search方法添加为资源的帖子(或任何适当的选项)选项,您可以将其添加到集合或成员 - 集合方法不会查找特定的项目ID url,适用于搜索方法。

resources :volunteers do 
  collection do
    post :search
  end
end