【问题标题】:Create a method like Devise's current_user to use everywhere创建一个像 Devise 的 current_user 这样的方法在任何地方使用
【发布时间】:2013-10-12 05:06:19
【问题描述】:

我允许我的用户拥有多个配置文件(用户有很多配置文件),其中一个是默认配置。在我的用户表中,我有一个 default_profile_id。

如何创建一个像 Devise 的 current_user 这样我可以在任何地方使用的“default_profile”?

我应该把这条线放在哪里?

default_profile = Profile.find(current_user.default_profile_id)

【问题讨论】:

    标签: ruby-on-rails ruby methods


    【解决方案1】:

    Devise 的 current_user 方法如下所示:

    def current_#{mapping}
      @current_#{mapping} ||= warden.authenticate(:scope => :#{mapping})
    end
    

    如您所见,@current_#{mapping} 正在被记忆。在你的情况下,你想使用这样的东西:

    def default_profile
      @default_profile ||= Profile.find(current_user.default_profile_id)
    end
    

    关于在任何地方使用它,我假设您想在控制器和视图中都使用它。如果是这种情况,您可以像这样在 ApplicationController 中声明它:

    class ApplicationController < ActionController::Base
    
      helper_method :default_profile
    
      def default_profile
        @default_profile ||= Profile.find(current_user.default_profile_id)
      end
    end
    

    helper_method 将允许您在视图中访问此记忆的 default_profile。在ApplicationController 中使用此方法允许您从其他控制器调用它。

    【讨论】:

      【解决方案2】:

      您可以通过在方法中定义来将此代码放入应用程序控制器中:

      class ApplicationController < ActionController::Base
        ...
        helper_method :default_profile
      
        def default_profile 
          Profile.find(current_user.default_profile_id)
        rescue
          nil 
        end
        ... 
      end
      

      并且,可以在您的应用程序中像 current_user 一样访问它。如果您调用 default_profile,它将为您提供配置文件记录(如果可用),否则为零。

      【讨论】:

      • 我实际上把它放在了用户模型中。
      • rescue nil 是一个糟糕的模式。如果没有找到,find_by_id(...) 也会返回 nil
      • 我收到 NameError: undefined local variable or method `default_persona' for main:Object
      • @AenTan: 只需定义:helper_method :default_profile,也更新了答案。
      • 感谢您一直以来的支持,但 AdamT 的回答确实提供了帮助,同时也提供了信息。不过真的很感谢。
      【解决方案3】:

      我会向用户添加一个方法profile 或定义一个has_one(首选)。如果您想要默认配置文件,则只需current_user.profile

      has_many :profiles
      has_one  :profile  # aka the default profile
      

      我不会实现快捷方式,但你想要:

      class ApplicationController < ActionController::Base
      
        def default_profile
          current_user.profile
        end
        helper_method :default_profile
      
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多