代码之家  ›  专栏  ›  技术社区  ›  nfm

Rails RESTful资源使用to_param作为包含分隔符的字段

  •  8
  • nfm  · 技术社区  · 17 年前

    我希望我的Rails 2.3.2应用程序能够响应并生成这样的URL:

    /websites/asd.com
    /websites/asd.com/dns_records/new
    

    在config/routes.rb中,我有:

    map.resources :websites, :has_many => :dns_records
    map.resources :dns_records, :belongs_to => :website
    

    然后,我可以访问以下资源:

    /websites/1
    /websites/1/dns_records
    

    通过修改我的网站模型,我可以生成更好的网址,如下所示:

    class Website < ActiveRecord::Base
        def to_param
            domain_name
        end
        ...
    end
    
    # app/views/websites/index.erb
    <% @websites.each do |w| %>
    <%= link_to "Show #{w}", website_path(w) %>
    <% end %>
    
    # Produces a link to:
    /websites/example_without_periods_in_name
    

    那么,有没有一种干净的方式来允许“。'RESTful URL中的字符?

    我尝试重新定义ActionController::Routing::SEPARATORS,使其不包含'。“这是解决问题的一个非常糟糕的方法。这会通过在生成的URL后附加“.:format”来混淆它们。

    非常感谢:)

    3 回复  |  直到 17 年前
        1
  •  4
  •   nfm    17 年前

    解决了这个问题,非常感谢 http://poocs.net/2007/11/14/special-characters-and-nested-routes (参见 http://dev.rubyonrails.org/ticket/6426 供进一步参考)

    map.resources :websites, :requirements => { :id => /[a-zA-Z0-9\-\.]+/ } do |websites|
        websites.with_options :requirements => { :website_id => /[a-zA-Z0-9\-\.]+/ }  do |websites_requirements|
            websites_requirements.resources :dns_records
        end
    end
    
    <%= link_to 'New DNS Record', new_website_dns_record_path(@website) %>
    
    # Produces the URL
    /websites/asd.com/dns_records/new
    

    呼叫

    websites.with_options
    

    websites_requirements.resources :accounts
    websites_requirements.resources :monthly_bandwidth_records
    etc.
    
        2
  •  1
  •   Oliver N.    17 年前

    '.:format' map.resources 的“。'在URL中。

    然而,也许你应该考虑改变你对 to_param

    def to_param
       domain_name.sub('.','_dot_')
    end
    

    /websites/asd_dot_com/dns_records/new
    /websites/asd_dot_com/