开发者

Handling an undefined variable

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?


Try defined? and not that it really matters but it's actually an operator.

<% if defined? video_id %>


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:

module VideoHelper 

  def show_video(video, options = {})
    options[:id] ||= ""
    render 'video', :video => video, :video_id => options[:id]
  end  

end

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.


Change the check to <% if defined? video_id %>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜