2012-07-17 68 views
2

我有添加新的生物資源和生物中的意見和鏈接:Rails路由 - 如何將範圍參數添加到url_for helper?

= link_to "Add new bio", [:new, :admin, :bio] 

如果我把資源:生物到的範圍是這樣的:

namespace :admin do  
    scope "/:bio_type", :defaults => {:bio_type => "company"} do 
    resources :bios 
    end 
end 

這不起作用

= link_to "Add new bio", [:new, :admin, :bio, { bio_type: params[:bio_type] }] 

我的問題是如何將範圍參數添加到url_for助手?鋼軌可以默認這樣做嗎?

p.s. new_admin_bio_path({bio_type:params [:bio_type]})工作正常,但它只是好奇

回答

3

我相信你不能使這個數組params到link_to。你必須使用polymorphic_pathnew_admin_bio_path({bio_type: params[:bio_type]})

的原因是,link_to電話url_for[:new, :admin, :bio, { bio_type: params[:bio_type] }],這就要求polymorphic_path這些PARAMS。

檢查源代碼url_forpolymorphic_url。 請注意,polymorphic_url需要2個參數 - record_or_hash_or_arrayoptions,但url_for僅調用一個參數。

def url_for(options = {}) 
    options ||= {} 
    case options 
    when String 
     options 
    when Hash 
     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 
    end 


    def polymorphic_path(record_or_hash_or_array, options = {}) 
    polymorphic_url(record_or_hash_or_array, options.merge(:routing_type => :path)) 
    end 

    def polymorphic_url(record_or_hash_or_array, options = {}) 
    if record_or_hash_or_array.kind_of?(Array) 
     record_or_hash_or_array = record_or_hash_or_array.compact 
     if record_or_hash_or_array.first.is_a?(ActionDispatch::Routing::RoutesProxy) 
     proxy = record_or_hash_or_array.shift 
     end 
     record_or_hash_or_array = record_or_hash_or_array[0] if record_or_hash_or_array.size == 1 
    end 

    record = extract_record(record_or_hash_or_array) 
    record = convert_to_model(record) 

    args = Array === record_or_hash_or_array ? 
     record_or_hash_or_array.dup : 
     [ record_or_hash_or_array ] 

    inflection = if options[:action] && options[:action].to_s == "new" 
     args.pop 
     :singular 
    elsif (record.respond_to?(:persisted?) && !record.persisted?) 
     args.pop 
     :plural 
    elsif record.is_a?(Class) 
     args.pop 
     :plural 
    else 
     :singular 
    end 

    args.delete_if {|arg| arg.is_a?(Symbol) || arg.is_a?(String)} 
    named_route = build_named_route_call(record_or_hash_or_array, inflection, options) 

    url_options = options.except(:action, :routing_type) 
    unless url_options.empty? 
     args.last.kind_of?(Hash) ? args.last.merge!(url_options) : args << url_options 
    end 

    args.collect! { |a| convert_to_model(a) } 

    (proxy || self).send(named_route, *args) 
    end 

所以,用scope選擇正確的調用應該聽起來像

polymorphic_path([:new, :admin, :bio], bio_type: params[:bio_type])