3

我有一个名为 Volunteers 的资源:

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

我添加了一个名为 search 的附加操作,但在路由文件中映射它时遇到问题:

root 'home#index'
resources :volunteers

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

4

1 回答 1

12

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

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

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

resources :volunteers do 
  collection do
    post :search
  end
end
于 2013-10-17T11:49:34.333 回答