处理未定义的变量
我在一个视图中渲染一个部分:
<%= render 'video', :video => @video, :video_id => 'video_show_id' %>
并在部分中包含此代码:
<% if video_id %>
<%= link_to "video", video.video_url, :class => "oembed", :id => video_id %>
<% else %>
<%= link_to "video", video.video_url, :class => "oembed" %>
<% end %>
问题是该部分在我的应用程序中的多个位置呈现,而在其他视图中我不想传递 :video_id< /code> 进入部分。因此,我的应用程序抛出
video_id
未定义的错误。我可以通过 :video_id =>; ""
到其他视图中的局部中,但由于局部在很多地方渲染,这有点痛苦。有没有更简单的方法来处理这个问题?
I render a partial in one view:
<%= render 'video', :video => @video, :video_id => 'video_show_id' %>
and have this code in the partial:
<% if video_id %>
<%= link_to "video", video.video_url, :class => "oembed", :id => video_id %>
<% else %>
<%= link_to "video", video.video_url, :class => "oembed" %>
<% end %>
The problem is that this partial gets rendered in a number of places in my app, and in those other views I do not want to pass :video_id
into the partial. Therefore my app throws an error that video_id
is undefined. I could pass :video_id => ""
into the partial in the other views, but since the partial is rendered in many places, that is kind of a pain. Is there a simpler way to handle this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试
define?
,这并不重要,但它实际上是一个 运算符。Try
defined?
and not that it really matters but it's actually an operator.我认为处理这个问题的更好方法是创建一个助手,然后管理需要提供给部分的变量的值。类似于:
现在,您不必在视图中保留那么长的渲染部分行,而是可以将其缩短为 show_video 调用。
另外,我发现从长远来看,这提供了更大的灵活性,并且我必须更少地考虑部分此时需要哪些变量以及它们是否已定义。
I think the better way to handle this is to create a helper that then manages the values of variables that need to fed to a partial. Something like:
Now, instead of having to have that long render partial line in your view, you get to shorten it to a show_video call.
Also, I've found that in the long term, this allows for a lot more flexibility and I have to think a lot less about what variables the partial needs at this time and whether or not they are defined.
将检查更改为
<% 如果已定义? video_id %>
Change the check to
<% if defined? video_id %>