0

一个用户可以有许多个人资料。每个配置文件都有自己的属性。并且用户可以随时随地从一个配置文件更改为另一个配置文件。

所以我想在控制器和视图中设置一个可用的方法或变量,我可以在其中设置用户的current_profile(如设计的current_user助手)。

我们尝试过使用ApplicationController私有方法和ApplicationHelper方法,但是当用户的昵称不可用时(通过 URL 参数设置)它不起作用。

这是 AppController 方法

...
private
  def set_profile
    if params[:username]
      @current_profile ||= Profile.where(username: params[:username]).entries.first
    else
     nil
    end
  end

这是 AppHelper 方法

def current_profile
  unless @current_profile.nil?
    @current_profile
  end
end

任何想法?

4

3 回答 3

1

创建一个扩展 ActionController::Base 的库(用于组织目的),并将“set_profile”和“current_profile”定义为辅助方法,然后在 ApplicationController 上调用它并调用它。

application_controller.rb

require 'auth'

before_filter :set_profile # sets the profile on every request, if any

lib/auth.rb

class ActionController::Base
  helper_method :set_profile, :current_profile

  protected

  def set_profile
    if params[:username]
      session[:user_profile] = params[:username]
      ...
    end
  end

  def current_profile
    @current_profile ||= if session[:user_profile]
      ...
    else
      ...
    end
  end

end

这样您就可以在代码(视图和控制器)的任何位置调用 current_profile。

于 2012-11-19T14:59:46.233 回答
0

如果您有User has_many :profiles可以在配置文件中添加current:boolean列的关系。然后:

def set_profile
  if params[:profile_id]
    @current_profile = Profile.find(params[:profile_id])
    @current_profile.current = true
  else
    nil
  end
end

# helper_method
def current_profile
   @current_profile
end
于 2012-11-19T05:19:15.847 回答
0

@current_profile因为 ApplicationController 的成员变量在您的助手中不可见。您应该在 Appcontroller 中创建访问器方法,例如:

def current_profile
  @current_profile
end

或通过

attr_accessor :current_profile

在助手中(确保控制器中的访问器不是私有的):

def current_profile
  controller.current_profile
end

但是您也可以自由地将其定义为仅助手,而根本不涉及控制器:

  def current_profile
    if params[:username]
      @current_profile ||= Profile.where(username: params[:username]).first
    end
  end

@current_profile如果没有指定参数,这将自动缓存您的数据库查询并自动返回 nil。所以不需要额外的else条款和额外的set_...方法

于 2012-11-19T08:37:39.023 回答