有关rails 4.0中link_to_if的问题,因为我刚刚升级了。旧的Rails 3版本没有问题。
简化示例:
link_to_if(user, "User", user.id)
content_tag(:span, "No User")
end
因此,对于给定的用户对象,它只是将其id设置为链接。我现在的问题是没有用户(零)/甚至可以在这里硬编码“假”。在旧的Rails 3中,它只是忽略了选项。
在Rails 4中,即使条件未满足,它也会奇怪地触发选项。为什么?即使条件已经发生,我真的需要检查零吗?
编辑,真实代码:
def link_to_previous_poster
link_to_if(@poster.prev, "< Previous".html_safe, poster_path(@poster.prev, :skip => skip_poster.to_i-1), :accesskey => 'h') do |name|
content_tag(:span, '< Previous'.html_safe, :class => "current")
end
end
如果@ poster.prev == nil,它会触发带有nil值的poster_path,这会导致路由错误。
浏览器错误是:
海报#show中的没有路由匹配{:action =&gt;“show”,:controller =&gt;“posters”,:id =&gt; nil,:format =&gt; nil,:skip =&gt; -1}缺少必需的密钥:[:id]
答案 0 :(得分:2)
poster_path(@poster.prev, :skip => skip_poster.to_i-1)
无论@poster.prev
是否为nil / falsy,此代码都将执行。你将上面的内容传递给link_to_if
作为论据;它将被评估,它的返回值将作为参数传递给link_to_if
。
我会改写帮手
def link_to_previous_poster
return content_tag(:span, '< Previous'.html_safe, :class => "current") if @poster.prev.blank?
link_to(@poster.prev, "< Previous".html_safe, poster_path(@poster.prev, :skip => skip_poster.to_i-1), :accesskey => 'h')
end