未定义的辅助方法
我有一个问题:
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 %>
...
有人帮助我吗?
i have a problem:
undefined method `avatar_url' for #<User:0x000000040783a8>
controller:
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
in view:
...
<%for user in @users %>
<%= image_tag avatar_url(user) %>, username: <%= user.username %>, e-mail: <%= user.email %>
<% end %>
...
Someone help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
关键是错误消息:
错误并不是因为辅助方法未定义:错误消息表明它是
User
类中缺少的方法。ApplicationController
中定义的方法尝试:您需要确保
User
类具有avatar_url
实例方法。The key is the error message:
The error isn't because the helper method is undefined: the error message indicates it's a missing method in the
User
class. The method defined inApplicationController
attempts:You need to make sure the
User
class has anavatar_url
instance method.更好的是,您可以从文件 ApplicationController 中删除“helper_method :avatar_url”行。
请在此处查看更多详细信息。 从 Rails 中的控制器调用辅助方法时出现“未定义方法”
因为,您应该在任何其他模块/帮助程序文件中定义帮助程序方法 xxx (helper_method :xxx)。因此,行 helper :all 自动包含您的所有帮助程序文件,然后只有您可以使用行 helper_method :xxx。这是有道理的。
无需将 ApplicationController 方法定义为辅助方法。您可以通过 avatar_url() 在任何控制器或视图中调用这些方法。
Better you can remove the line "helper_method :avatar_url" from the file ApplicationController.
Please see more details here. "undefined method" when calling helper method from controller in Rails
Because, you should define the helper method xxx (helper_method :xxx) in any other module/helper file. So, the line helper :all automatically include all your helper files then only you can use the line helper_method :xxx. It makes sense.
No need to define the ApplicationController methods as a helper method. You can call those methods in any controller or views in simply avatar_url().