【问题标题】:Accessing current_user in Rails route在 Rails 路由中访问 c​​urrent_user
【发布时间】:2016-01-28 05:34:43
【问题描述】:

请原谅我...我知道还有其他类似标题的帖子,但我没有看到我的问题所以...

我正在尝试创建一个 url mysite.com/myusername/profile,我想知道如何为此创建路由。目前,user#profile 的 URL 就是 mysite.com/user/profile,但我想让它更具体一些,比如说每个用户都有一个像 JohnnySmith 这样的用户名,URL 是 mysite.com/JohnnySmith/轮廓。我在想类似的事情

get "/#{current_user.username}", to: "user#profile", as: user_profile 

但我知道这是不正确的。

我还应该提到,任何人都无法访问 mysite.com/JohnnySmith/profile.... 当前用户必须是 JohnnySmith。

有人可以帮忙吗?谢谢。

【问题讨论】:

标签: ruby-on-rails devise routes url-routing


【解决方案1】:

如果要在路由中传递参数,应该是

get "/:username/profile", to: "user#profile", as: user_profile

请看http://guides.rubyonrails.org/routing.html#naming-routes

然后您可以在控制器中使用params[:username] 来验证用户是否喜欢

if current_user.username != params[:username]
   # redirect to error page

或者您可以使用cancancan gem 来执行此操作。

【讨论】:

    【解决方案2】:

    您需要使用friendly_idCanCanCan 进行授权。


    本质上,您要做的是允许 Rails 通过参数处理用户名。这可以在没有 friendly_id 的情况下完成,但有点 hacky。

    使用friendly_id gem 将允许您使用以下内容:

    #Gemfile
    gem "friendly_id"
    
    $ rails generate friendly_id
    $ rails generate scaffold user name:string slug:string:uniq
    $ rake db:migrate
    
    #app/models/user.rb
    class User < ActiveRecord::Base
       extend FriendlyID
       friendly_id :username, use: [:finders, :slugged]
    end
    

    然后您就可以使用:

    #config/routes.rb
    resources :users, path: "", only: [] do
       get :profile, action: :show, on: :member #-> url.com/:id/profile
    end
    
    #app/controllers/users_controller.rb
    class UsersController < ApplicationController
       def show
          @user = User.find params[:id]
       end
    end
    

    这会自动将params[:id] 转换为User 模型的slug 属性:

    <%= link_to "Profile", user_profile_path(current_user) %>
    # -> url.com/:current_user_name/profile
    

    --

    下一个阶段是授权

    使用CanCanCan 应该使只有current_user 可以查看他们的个人资料:

    #Gemfile
    gem "cancancan"
    
    #app/models/ability.rb
    class Ability
      include CanCan::Ability
    
      def initialize(user)
        user ||= User.new # guest user (not logged in)
        can :read, User, id: user.id
      end
    end
    

    然后您可以在 users 控制器中使用 load_and_authorize_resource

    #app/controllers/users_controller.rb
    class UsersController < ApplicationController
       load_and_authorize_resource
    
       def show
       end
    end
    

    【讨论】:

      猜你喜欢
      • 2019-01-31
      • 1970-01-01
      • 1970-01-01
      • 2010-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多