如何在部分public_activity gem中访问current_user?

时间:2015-03-25 10:34:48

标签: ruby-on-rails ruby ruby-on-rails-3 devise public-activity

当我尝试访问部分文件中的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值。

我不明白这是什么问题。

请帮帮我。 提前致谢。

2 个答案:

答案 0 :(得分:1)

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

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

end 

这会在每个请求上记录控制器,允许我们从模型中访问它。我们可以通过添加要跟踪的所有者选项在模型中执行此操作。

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

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

答案 1 :(得分:0)

跟踪用户的示例。

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 + ")"