繁体   English   中英

Ruby on Rails的未定义局部变量或方法`profile'

[英]Undefined local variable or method `profile' for Ruby on Rails

在我的静态页面home.html.erb中,我有一个对StaticPagesController的引用。 我相信我做得正确,但是仍然得到未定义的局部变量或方法“ profile”。

静态页面控制器

class StaticPagesController < ApplicationController

    def profile
        redirect_to profile_path(current_user)
    end 
end

home.html.erb

<% if logged_in? %>
    <% profile %>
<% else %>
    <h1>Welcome to myProjects</h1>
    <%= link_to "Sign up!", signup_path, class: "btn btn-lg btn-primary" %>
<% end %>

好吧,我认为您正在尝试从视图访问在控制器中定义的方法。 抱歉,这是不可能的。 使用MVC,您无法像这样在控制器中触发方法。 理想情况下,您应该在app / helpers / application_helper.rb或app / helpers / static_pages_helper.rb下定义一个助手方法。 尝试按您的方式访问它会导致看到错误。

您需要将def profile作为辅助方法,以便可以查看此方法。 只需在def profile方法下面添加以下行:

 helper_method :profile

您的最终课程将如下所示:

 class StaticPagesController < ApplicationController

    def profile
      redirect_to profile_path(current_user)
    end 

    helper_method :profile
  end

暂无
暂无

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

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