Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #7356: add_argument_to_activerecord_to_param.patch

File add_argument_to_activerecord_to_param.patch, 2.4 kB (added by bscofield, 3 years ago)
  • activerecord/test/base_test.rb

    old new  
    15851585  def test_to_param_should_return_string 
    15861586    assert_kind_of String, Client.find(:first).to_param 
    15871587  end 
     1588   
     1589  def test_to_param_can_return_arbitrary_method 
     1590    assert_equal topics(:first).title.to_s, topics(:first).to_param(:title) 
     1591  end 
     1592   
     1593  def test_to_param_returns_id_on_unknown_method 
     1594    assert_equal topics(:first).id.to_s, topics(:first).to_param(:foo) 
     1595  end 
    15881596 
     1597  def test_to_param_returns_id_by_default 
     1598    assert_equal topics(:first).id.to_s, topics(:first).to_param 
     1599  end 
     1600 
    15891601  # FIXME: this test ought to run, but it needs to run sandboxed so that it 
    15901602  # doesn't b0rk the current test environment by undefing everything. 
    15911603  # 
  • activerecord/lib/active_record/base.rb

    old new  
    15221522      end 
    15231523 
    15241524      # Enables Active Record objects to be used as URL parameters in Action Pack automatically. 
    1525       def to_param 
    1526         # We can't use alias_method here, because method 'id' optimizes itself on the fly. 
    1527         (id = self.id) ? id.to_s : nil # Be sure to stringify the id for routes 
     1525      def to_param(method = :id) 
     1526        if method != :id && self.respond_to?(method)  
     1527          id = (instance_eval method.to_s)  
     1528        else 
     1529          id = self.id 
     1530        end  
     1531        id ? id.to_s : nil 
    15281532      end 
    15291533 
    15301534      def id_before_type_cast #:nodoc: 
  • actionpack/lib/action_controller/routing.rb

    old new  
    11791179 
    11801180        options_as_params = options[:controller] ? { :action => "index" } : {} 
    11811181        options.each do |k, value| 
    1182           options_as_params[k] = value.to_param 
     1182          # check for a connection to see if the value is an ActiveRecord::Base model; if so, pass the 
     1183          #   key to the to_param method to get the appropriate value back 
     1184          options_as_params[k] = value.respond_to?(:connection) ? value.to_param(k) : value.to_param 
    11831185        end 
    11841186        options_as_params 
    11851187      end