Ruby on rails 创建一个类似designe'的方法;s当前用户可在任何地方使用

Ruby on rails 创建一个类似designe'的方法;s当前用户可在任何地方使用,ruby-on-rails,ruby,methods,Ruby On Rails,Ruby,Methods,我允许我的用户有多个配置文件(用户有多个配置文件),其中一个是默认配置文件。在我的用户表中,我有一个默认的\u profile\u id 我如何创建一个“默认_配置文件”,就像Desive的当前_用户一样,我可以在任何地方使用它 我应该把这条线放在哪里 default_profile = Profile.find(current_user.default_profile_id) 通过在方法中定义以下内容,可以将此代码放入应用程序控制器中: class ApplicationController

我允许我的用户有多个配置文件(用户有多个配置文件),其中一个是默认配置文件。在我的用户表中,我有一个默认的\u profile\u id

我如何创建一个“默认_配置文件”,就像Desive的当前_用户一样,我可以在任何地方使用它

我应该把这条线放在哪里

default_profile = Profile.find(current_user.default_profile_id)

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

class ApplicationController < ActionController::Base
  ...
  helper_method :default_profile

  def default_profile 
    Profile.find(current_user.default_profile_id)
  rescue
    nil 
  end
  ... 
end
class ApplicationController

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

designe当前的_用户方法如下所示:

def current_#{mapping}
  @current_#{mapping} ||= warden.authenticate(:scope => :#{mapping})
end
def default_profile
  @default_profile ||= Profile.find(current_user.default_profile_id)
end
如您所见,
@current_35;{mapping}
正在被记忆。在您的情况下,您可能希望使用以下内容:

def current_#{mapping}
  @current_#{mapping} ||= warden.authenticate(:scope => :#{mapping})
end
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
class ApplicationController

helper\u方法
将允许您在视图中访问此已记忆的默认配置文件。在
应用程序控制器
中使用此方法,您可以从其他控制器调用它。

我会向用户添加一个方法
配置文件
,或者定义一个
有一个
(首选)。如果您想要默认配置文件,则它只是当前用户配置文件

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
class ApplicationController
我实际上把它放在了用户模型中。
rescue nil
是一个糟糕的模式
find_by_id(…)
如果找不到,也会返回
nil
。我得到NameError:main的未定义局部变量或方法“default_persona”:Object@AenTan:仅定义:helper\u方法:默认\u配置文件,也更新了答案。感谢所有的时间,但实际上是阿达姆的答案真的很有帮助,同时也是信息性的。但真的谢谢你。