【问题标题】:Ruby / Rails - NoMethodError in Pages#home - Partial ViewRuby / Rails - Pages#home 中的 NoMethodError - 部分视图
【发布时间】:2017-02-07 04:14:27
【问题描述】:

错误: Pages#home 中的 NoMethodError(强调文​​本未定义方法 `profile' for nil:NilClass


控制器: pages_controller.rb

    class PagesController < ApplicationController
before_action :authenticate_user!, except:  [:landing, :home, :plan]

def home
    @contributor_plan = Plan.find(1)
    @elitecontributor_plan = Plan.find(2)
    @technician_plan = Plan.find(3)
    @elitetechnician_plan = Plan.find(4)
    @center_plan = Plan.find(5)
    @elitecenter_plan = Plan.find(6)
    @affair_plan = Plan.find(7)
    @eliteaffair_plan = Plan.find(8)
end

【问题讨论】:

    标签: ruby-on-rails variables model-view-controller methods variable-assignment


    【解决方案1】:

    问题是@usernil,你不能在nil 对象上调用profile 方法。

    如果你仔细看,你的before_filter

    before_action :authenticate_user!, except:  [:landing, :home, :plan]
    

    没有为home 操作调用authenticate_user! 方法(在except 中指定)。因此,您实际上无权访问当前登录的用户。

    因此,您必须对home 操作的用户进行身份验证。将您的before_filter 修改为

    before_action :authenticate_user!, except:  [:landing, :plan]
    

    另外,devise 公开了一个名为current_user 的方法,您可以使用该方法找到当前登录的用户。所以,你的视图应该使用current_user 而不是@user

    <%= image_tag current_user.profile.avatar.url %>
    

    【讨论】:

    • 我已经修改了 before_filter。谢谢你。但是,错误消息仍然存在。我假设我没有在 pages_controller 中正确定义“用户”。这是正确的吗?
    • @NathanielRand 更新了我的答案。看看,如果它解决了问题,请告诉我。
    • 问题已解决。你的贡献是有价值的。所以 Devise 的“current_user”可以应用于任何“authenticate_user!”页面?
    • @NathanielRand 只要你在控制器动作中调用了authenticate_user!方法,你就可以在视图中使用current_user
    猜你喜欢
    • 2015-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多