我在 View 中有这个 RoR 片段:
<%= link_to_unless(@posts_pages[:previous].nil?,
"Previous",
blog_with_page_path(:page_num => @posts_pages[:previous])) %>
这里 blog_with_page 是一个命名路由。如果 @posts_pages[:previous].nil?
为 false
(如预期),并且链接已正确生成,则该代码段有效。但是,当 @posts_pages[:previous].nil?
为 true
时,我不是简单地获取 "Previous"
字符串,而是得到一个错误告诉我无法使用 :page_num=>nil
生成路线。这是预期的行为吗?如果满足条件,则不应评估路线代码,不是吗?
这是完整的错误:
blog_with_page_url 无法从 {:page_num=>nil, :action=>"show", :controller=>"pages"} 生成,预期:{:action=>"show", :controller=>"pages"},差异:{:page_num=>nil}
我一直在查看 link_to_unless
代码,但我不明白为什么会收到错误,因为它应该只返回名称:
# File actionpack/lib/action_view/helpers/url_helper.rb, line 394
def link_to_unless(condition, name, options = {}, html_options = {}, &block)
if condition
if block_given?
block.arity <= 1 ? capture(name, &block) : capture(name, options, html_options, &block)
else
name
end
else
link_to(name, options, html_options)
end
end
我正在使用 Rails 2.3.11 和 Ruby 1.8.7
干杯!
最佳答案
因为 Ruby 不是一种懒惰的语言,blog_with_page_path(:page_num => @posts_pages[:previous])
一旦您调用它,就会立即对其进行求值,无论该值是否被 link_to_unless
使用。 .
关于ruby-on-rails - link_to_unless问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5732689/