[英]actionview::template::error(undefined method 'html_safe' for nil:NilClass)
I am a beginer in ruby and I want to write a plugin for redmine. 我是红宝石的初学者,我想为redmine写一个插件。 I have written a plugin which was running since I use 'flash[:var]' in a controller of my plugin. 我写了一个运行的插件,因为我在我的插件的控制器中使用'flash [:var]'。 Now when I want to access to all my pages I have an error message that I not understand. 现在当我想访问我的所有页面时,我收到一条我不理解的错误消息。
Ruby version : ruby 1.9.3p484 Ruby版本:ruby 1.9.3p484
Rails version : rails 3.2.19 Rails版本:rails 3.2.19
this is the error message 这是错误消息
thank you for your answers. 谢谢您的回答。
EDIT: 编辑:
You can convert the nil
to string
using .to_s
method 您可以使用.to_s
方法将nil
转换为string
Problem 问题
When you try to call .html_safe
on nil
value it will throw the following error 当您尝试在nil
值上调用.html_safe
时,它将引发以下错误
NoMethodError: undefined method `html_safe' for nil:NilClass
For example 例如
[8] project_rails » html_content = nil
=> nil
[9] project_rails » html_content.html_safe
NoMethodError: undefined method `html_safe' for nil:NilClass
from (pry):9:in `__pry__'
Solution 解
You can convert the nil
to string using .to_s
您可以使用.to_s
将nil
转换为字符串
For example 例如
[10] project_rails » html_content = nil
=> nil
[11] project_rails » html_content.to_s.html_safe
=> ""
[12] project_rails »
So your code should be like this 所以你的代码应该是这样的
def render_flash_messages
s = ''
flash.each do |k,v|
s << content_tag('div',v.to_s.html_safe, :class => "flash #{k}", :id => "flash_#{k}")
end
s.html_safe
end
It seems like you ran into situations in which you have nil
values in your flash
. 您似乎遇到了flash
nil
值的情况。 Imagine you have a flash
like { error: nil }
, then you would call v.html_safe
in the content_tag
- what will cause the error. 想象一下你有一个类似{ error: nil }
的flash
,然后你会在content_tag
调用v.html_safe
- 这将导致错误。
You might want to extract all values from the flash
that are present?
您可能想要从flash
中提取所有值present?
, before calling content_tag
: ,在调用content_tag
之前:
def render_flash_messages
flash.select { |k, v| v.present? }.map do |type, text|
content_tag(:div, text.html_safe, class: "flash #{type}", id: "flash_#{typ}")
end.join
end
The problem is that you put nil
into the flash which is something Redmine's render_flash_messages
method is not designed to handle. 问题是你把nil
放入flash中,这是Redmine的render_flash_messages
方法不能处理的东西。
Changing that method to deal with nil values will work but is not something you should do from a Redmine plugin. 更改该方法以处理nil值将起作用,但您不应该从Redmine插件中执行此操作。 Instead, find out where and why in your plugin you put nil
into the flash and simply don't do it. 相反,找出你的插件在哪里以及为什么你把nil
放入闪存并且根本不这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.