类似Github的用户名网址

时间:2012-03-05 22:30:12

标签: ruby-on-rails rails-routing

我有这条路线让我为像这样的用户构建自定义网址 / thisismyname,它工作正常。但是,当我查看日志时,有 我不喜欢的东西......

当我点击/ gregory时,这就是发生的事情: 1.去public_profile#public#Good 2.点击/资产并试图找到具有资产令牌的用户#Not good

我认为我的约束会避免这种情况,但它似乎不是......

class PublicProfileConstraint
  def self.matches?(request)
     !['assets', 'admin'].include?(request.session[:token])
  end
end

get "/:token" => "profiles#public", :as => :public_profile,
    :constraints => PublicProfileConstraint

这是日志:

Started GET "/gregory" for 127.0.0.1 at 2012-03-05 12:44:43 -0800
  Processing by ProfilesController#public as HTML
  Parameters: {"token"=>"gregory"}
  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE
"users"."id" = ? LIMIT 1  [["id", 1]]
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE
"users"."token" = 'gregorymarcilhacy' LIMIT 1
Rendered profiles/_modal.haml (0.1ms)
....
Rendered profiles/show.haml within layouts/application (154.7ms)
Completed 200 OK in 431ms (Views: 174.0ms | ActiveRecord: 5.5ms)

... Redering js files ...

# I DONT WANT THIS
Started GET "/assets/" for 127.0.0.1 at 2012-03-05 12:44:45 -0800
Served asset  - 404 Not Found (10ms)
  Processing by ProfilesController#public as */*
  Parameters: {"token"=>"assets"}
  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE
"users"."id" = ? LIMIT 1  [["id", 1]]
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE
"users"."token" = 'assets' LIMIT 1
Redirected to http://localhost:3000/
Completed 302 Found in 312ms

... Rendering images ...

# AND I DONT WANT THIS
Started GET "/" for 127.0.0.1 at 2012-03-05 12:44:45 -0800
  Processing by LandingController#landing as */*
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE
"users"."id" = ? LIMIT 1  [["id", 1]]
Rendered landing/landing.haml within layouts/landing (0.8ms)
Completed 200 OK in 288ms (Views: 23.5ms | ActiveRecord: 2.2ms)

1 个答案:

答案 0 :(得分:1)

您正在搜索request.session以获取令牌,但这将始终失败,因为这是会话存储而不是请求参数。您可能希望在约束类中等效params[:token]request object documentation表示request.path_parameters[:token]可能包含您要查找的值。