繁体   English   中英

如何在public_activity gem中访问current_user?

[英]How to access current_user in partial of public_activity gem?

当我尝试访问部分文件中的current_user时,它将包含nil值。

我将devise gem用于登录过程。 我还使用public_activity gem生成通知。

我有如下的通知控制器。

def index
    @activities = PublicActivity::Activity.all      
end

在views / notifications / index.html.erb中

<%= render @activities %>

现在在views / public_activity / commontator_comment / _create.html.erb中

在此部分中,我要访问current_user,但其中包含nil值。

我不明白是什么问题。

请帮我。 提前致谢。

在应用程序控制器中,您需要包含一个模块

class ApplicationController < ActionController::Base  
  include PublicActivity::StoreController       

end 

这会记录每个请求的控制器,使我们可以从模型中访问它。 我们可以在模型中通过向跟踪添加所有者选项来做到这一点。

tracked owner: ->(controller, model) { controller.current_user } 

您可以在此处详细了解此信息http://asciicasts.com/episodes/406-public-activity

跟踪用户示例。

application_controller.rb

class ApplicationController < ActionController::Base
  include PublicActivity::StoreController

  [.....]

  # Only if devise is not used
  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end
end

activities_controller.rb

class ActivitiesController < ApplicationController
  def index
    @activities = PublicActivity::Activity.order("created_at desc")
  end
end

user.rb

class User < ActiveRecord::Base
  include PublicActivity::Common
  [...]
end

users_controller.rb

class UsersController < ApplicationController      

  def my_method
    [...]
      respond_to do |format|
      if @my_object.save
      @my_object.create_activity :create, owner: current_user 
    [...] 
  end
end

应用程序/视图/活动/ index.html.haml

- @activities.each do |a|
  = render_activity a

其他意见

/app
  /views
    /public_activity
      /user
        _create.html.haml
        _destroy.html.haml
        [_all_methods.html.haml] 

查看范例

 = a.owner.name + " " + a.owner.firstname
 created the user
 = a.trackable.name + " " + a.trackable.firstname + " (" + a.trackable.email + ")"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM