【问题标题】:Undefined local variable or method `profile' for Ruby on RailsRuby on Rails 的未定义局部变量或方法“配置文件”
【发布时间】:2016-07-24 06:57:14
【问题描述】:

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

静态页面控制器

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 %>

【问题讨论】:

  • Pragash 的答案是正确的,但你到底想做什么?

标签: ruby-on-rails ruby


【解决方案1】:

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

 helper_method :profile

你的最后一堂课看起来像这样:

 class StaticPagesController < ApplicationController

    def profile
      redirect_to profile_path(current_user)
    end 

    helper_method :profile
  end

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多