2011-05-07 195 views
1

为什么Rails会在anchor元素的属性href中创建当前页面的路径,而不是在发送异常时向我的link_to方法传递与任何资源无关的实例变量(和等于nil)?Ruby on Rails。 link_to不会引发异常

下面是一个例子:

路线

# app/config/routes.rb 
Example::Application.routes.draw do 
    resource :example 
end 

HAML

-# app/views/examples/show.html.haml 
%div 
    = link_to 'Non-existent resource', @ne_resource 

HTML

<!-- http://localhost/example --> 
<div> 
    <a href="/example">Non-existent resource</a> 

谢谢。

Debian GNU/Linux 6.0.1;

Ruby 1.9.2;

Ruby on Rails 3.0.6。

回答

2

如果你看看link_to方法,它使用url_for方法链接到URL。

def link_to(*args, &block) 
    if block_given? 
     options  = args.first || {} 
     html_options = args.second 
     link_to(capture(&block), options, html_options) 
    else 
     name   = args[0] 
     options  = args[1] || {} 
     html_options = args[2] 

     html_options = convert_options_to_data_attributes(options, html_options) 
     url = url_for(options) #THIS GETS CALLED 

     href = html_options['href'] 
     tag_options = tag_options(html_options) 

     href_attr = "href=\"#{html_escape(url)}\"" unless href 
     "<a #{href_attr}#{tag_options}>#{html_escape(name || url)}</a>".html_safe 
    end 
    end 

网址为

def url_for(options = {}) 
    options ||= {} 
    url = case options 
    when String 
     options 
    when Hash #THIS CASE IS TRUE 
     options = options.symbolize_keys.reverse_merge!(:only_path => options[:host].nil?) 
     super 
    when :back 
     controller.request.env["HTTP_REFERER"] || 'javascript:history.back()' 
    else 
     polymorphic_path(options) 
    end 

    url 
    end 

从上面可以看到,url_for是有效的,而不选择或用nilClass,它的目的不是要引发异常。如果您在使用link_to时需要错误,请确保在上例中使用动态“路径”辅助方法new_example_path。

2

当传递nil, nil参数时,我向DHH(Rails的创建者)询问了有关link_to行为的密切相关的问题。我希望它根本不会渲染标签,而不是让我在调用之前检查nils。他亲切地说:

https://twitter.com/dhh/status/198487578352156672

这个答案的本质适用于你的问题。当它交给nil时,它需要做些事情。 Gazler指出技术上发生了什么,但是DHH的回应显示了一个更高层次的“为什么?”。 url_for方法没有任何参数,当前页面是一个合理的默认值。