假设我有一个用脚手架创建的模块名称Server。我希望将网址“www.example.com/server/”重定向到第一个存在的服务器对象。例如,重定向到“www.example.com/server/2”。
如何使用routes.rb(或任何其他方式)来完成?
route.rb:
Rails.application.routes.draw do
resources :servers
end
服务器控制器:
class ServersController < ApplicationController
before_action :set_server, only: [:show, :edit, :update, :destroy]
# GET /servers
# GET /servers.json
def index
@servers = Server.all
end
....
答案 0 :(得分:1)
你可以把
redirect_to server_path(Server.first) and return
在您的index
方法中,当您调用索引操作时,它会重定向您。
并且仅限于@richfisher's回答(这可能是更合适的方式)。
resources :servers, except: [:index] # this won't generate redundant routes
get '/servers/' => 'servers#first' #note this is now accessible via "server_path" instead of "servers_path" helper.
答案 1 :(得分:0)
为了它的价值,我会这样做:
#config/routes.rb
resources :servers, except: :index do
get "", action: :show, id: Server.first.id, on: :collection
end
这样,您就可以在超高效设置中使用show
操作代替index
:
#app/controllers/servers_controller.rb
class ServersController < ApplicationController
def show
@server = Server.find params[:id]
end
end