Skip to content

Commit

Permalink
Merge pull request #6588 from nbibler/polymorphic_to_model
Browse files Browse the repository at this point in the history
Correct the use of to_model in polymorphic routing
  • Loading branch information
josevalim committed Jun 1, 2012
1 parent 3449b75 commit 5c565a2
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
8 changes: 7 additions & 1 deletion actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def polymorphic_url(record_or_hash_or_array, options = {})
end

record = extract_record(record_or_hash_or_array)
record = record.to_model if record.respond_to?(:to_model)
record = convert_to_model(record)

args = Array === record_or_hash_or_array ?
record_or_hash_or_array.dup :
Expand All @@ -122,6 +122,8 @@ def polymorphic_url(record_or_hash_or_array, options = {})
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

Expand Down Expand Up @@ -152,6 +154,10 @@ def action_prefix(options)
options[:action] ? "#{options[:action]}_" : ''
end

def convert_to_model(object)
object.respond_to?(:to_model) ? object.to_model : object
end

def routing_type(options)
options[:routing_type] || :url
end
Expand Down
28 changes: 27 additions & 1 deletion actionpack/test/activerecord/polymorphic_routes_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,24 @@ class Series < ActiveRecord::Base
self.table_name = 'projects'
end

class ModelDelegator < ActiveRecord::Base
self.table_name = 'projects'

def to_model
ModelDelegate.new
end
end

class ModelDelegate
def self.model_name
ActiveModel::Name.new(self)
end

def to_param
'overridden'
end
end

module Blog
class Post < ActiveRecord::Base
self.table_name = 'projects'
Expand All @@ -50,6 +68,7 @@ def setup
@bid = Bid.new
@tax = Tax.new
@fax = Fax.new
@delegator = ModelDelegator.new
@series = Series.new
@blog_post = Blog::Post.new
@blog_blog = Blog::Blog.new
Expand Down Expand Up @@ -439,6 +458,13 @@ def test_uncountable_resource
end
end

def test_routing_a_to_model_delegate
with_test_routes do
@delegator.save
assert_equal "http://example.com/model_delegates/overridden", polymorphic_url(@delegator)
end
end

def with_namespaced_routes(name)
with_routing do |set|
set.draw do
Expand Down Expand Up @@ -469,6 +495,7 @@ def with_test_routes(options = {})
resource :bid
end
resources :series
resources :model_delegates
end

self.class.send(:include, @routes.url_helpers)
Expand Down Expand Up @@ -516,5 +543,4 @@ def with_admin_and_site_test_routes(options = {})
yield
end
end

end

0 comments on commit 5c565a2

Please sign in to comment.