Rails 4:路由范围和会话cookie

时间:2013-09-23 10:52:10

标签: ruby-on-rails ruby cookies scope routes

如果我有以下routes.rb

MyApp::Application.routes.draw do
  resources :foo
end

生成会话cookie:

$ curl -s -D - http://127.0.0.1:3000/foo -o /dev/null | grep Set-Cookie
Set-Cookie: _myapp_session=...; path=/; HttpOnly
$

但如果我将路线改为:

MyApp::Application.routes.draw do
  scope "/bar" do
    resources :foo
  end
end

没有cookie:

$ curl -s -D - http://127.0.0.1:3000/bar/foo -o /dev/null | grep Set-Cookie
$

会话cookie和路由范围之间的关系是什么?如何在两种情况下保持相同的行为?

1 个答案:

答案 0 :(得分:1)

行。解决了我的问题。是与资产前缀相关的东西。重现的步骤:

创建一个新的rails应用程序:

$ rails new sample --skip-active-record

在Gemfile中取消注释therubyracer gem。这与问题无关,只是我们可以运行应用程序。

生成新资源:

$ rails generate resource foo

将一些代码添加到使用会话的控制器(app/controllers/foos_controller.rb):

class FoosController < ApplicationController
    def index
        session[:foo] = 'bar'
        render nothing: true
    end
end

测试:

$ curl -s -D - http://127.0.0.1:3000/foos -o /dev/null | grep Set-Cookie
Set-Cookie: _sample_session=R1..; path=/; HttpOnly

更改资源的范围(config/routes.rb):

Sample::Application.routes.draw do
  scope '/bar' do
    resources :foos
  end
end

再次测试:

$ curl -s -D - http://127.0.0.1:3000/bar/foos -o /dev/null | grep Set-Cookie
Set-Cookie: _sample_session=Sk...; path=/; HttpOnly

更改资产前缀(config/application.rb):

module Sample
  class Application < Rails::Application
    config.assets.prefix = '/bar'
  end
end

再次测试。没有饼干:

$ curl -s -D - http://127.0.0.1:3000/bar/foos -o /dev/null | grep Set-Cookie
$

再次更改资产前缀:

module Sample
  class Application < Rails::Application
    config.assets.prefix = '/bar/assets'
  end
end

再次测试:

$ curl -s -D - http://127.0.0.1:3000/bar/foos -o /dev/null | grep Set-Cookie
Set-Cookie: _sample_session=L3...; path=/; HttpOnly