【问题标题】:undefined helper method未定义的辅助方法
【发布时间】:2011-11-19 02:33:10
【问题描述】:

我有一个问题:

undefined method `avatar_url' for #<User:0x000000040783a8>

控制器:

class ApplicationController < ActionController::Base
  protect_from_forgery
  helper :all
  helper_method :avatar_url

  protected

  def avatar_url(user)
    if user.avatar_url.present?
      user.avatar_url
    else
      default_url = "#{root_url}images/guest.png"
      gravatar_id = Digest::MD5.hexdigest(user.email.downcase)
      "http://gravatar.com/avatar/#{gravatar_id}.png?s=48&d=#{CGI.escape(default_url)}"
    end
  end
end

在视图中:

...
<%for user in @users %>
  <%= image_tag avatar_url(user) %>, username: <%= user.username %>, e-mail: <%= user.email %>
<% end %>
...

有人帮帮我吗?

【问题讨论】:

  • User 类中有avatar_url 方法吗?错误来自对user.avatar_url 的调用,而不是应用程序帮助方法本身。
  • 谢谢建议,我会检查一下。

标签: ruby-on-rails helper


【解决方案1】:

关键是错误信息:

undefined method `avatar_url' for #<User:0x000000040783a8>

错误不是因为辅助方法未定义:错误消息表明它是User 类中缺少的方法。 ApplicationController中定义的方法尝试:

def avatar_url(user)
  if user.avatar_url.present?
    user.avatar_url
  #...

您需要确保User 类具有avatar_url 实例方法。

【讨论】:

    【解决方案2】:

    最好从文件 ApplicationController 中删除“helper_method :avatar_url”行。
    请在此处查看更多详细信息。 "undefined method" when calling helper method from controller in Rails

    因为,您应该在任何其他模块/帮助文件中定义帮助方法 xxx (helper_method :xxx)。因此,行 helper :all 会自动包含所有帮助文件,然后只有您可以使用行 helper_method :xxx。有道理。

    无需将 ApplicationController 方法定义为辅助方法。您可以在任何控制器或视图中调用这些方法,只需 avatar_url()。

    【讨论】:

    • 没有从控制器调用助手。
    猜你喜欢
    • 2013-06-11
    • 2015-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多