在Rails的应用程序控制器中调用当前用户

时间:2018-09-08 00:51:46

标签: ruby-on-rails devise

大家好,我是Rails的新手,如果我的问题很简单或很愚蠢,请理解我。我当前正在使用devise gem,并且尝试将模式信息放入我的application.html.erb中,以便模式信息始终显示在顶部,但是我得到的错误消息是

  

ApplicationController:Class的未定义局部变量或方法“ current_user”

我应该在哪里修复从Post.rb中的Application.html.erb调用记录的问题?感谢您的帮助!

Application.html.erb

<ul class="nav navbar-nav navbar-right">
   <% if user_signed_in? %> 
     <li><%=link_to 'Sign out', destroy_user_session_path, method: 'delete' %></li>
     <%=render "post_list", post_list: @post_list%> //I tried to call this
<% else %> 
   <li><%=link_to 'Sign in',  new_user_session_path %></li>
   <li><%=link_to 'Sign up',  new_user_registration_path %></li>
<% end %>
</ul>

应用程序控制器

class ApplicationController < ActionController::Base
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected

  @post_list = Post.where(user_id: current_user).list?

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:name])
    devise_parameter_sanitizer.permit(:account_update, keys: [:name])
  end
end

1 个答案:

答案 0 :(得分:1)

这是您可以在current_user中访问ApplicationController

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  def current_user_posts?
    @post_list = Post.where(user_id: current_user).list? // current_user should work here.
  end

end