Permalink
Browse files

`#to_param` returns `nil` if `to_key` returns `nil`. Closes #11399.

The documentation of `#to_key` (http://api.rubyonrails.org/classes/ActiveModel/Conversion.html#method-i-to_key)
states that it returns `nil` if there are no key attributes. `to_param` needs
to be aware of that fact and return `nil` as well.

Previously it raised the following exception:

```
  1) Error:
ConversionTest#test_to_param_returns_nil_if_to_key_is_nil:
NoMethodError: undefined method `join' for nil:NilClass
    /Users/senny/Projects/rails/activemodel/lib/active_model/conversion.rb:65:in `to_param'
    /Users/senny/Projects/rails/activemodel/test/cases/conversion_test.rb:34:in `block in <class:ConversionTest>'
```

Conflicts:
	activemodel/CHANGELOG.md
  • Loading branch information...
1 parent d5e684f commit 98e2ae95bcb3e8da9c29ce2dae59ca6b6349b0e1 @senny senny committed Feb 4, 2014
View
@@ -1,3 +1,7 @@
+* `#to_param` returns `nil` if `#to_key` returns `nil`. Fixes #11399.
+
+ *Yves Senn*
+
## Rails 4.0.1 (November 01, 2013) ##
* Fix `has_secure_password` to honor bcrypt-ruby's cost attribute.
@@ -62,7 +62,7 @@ def to_key
# person = Person.create
# person.to_param # => "1"
def to_param
- persisted? ? to_key.join('-') : nil
+ (persisted? && key = to_key) ? key.join('-') : nil
end
# Returns a +string+ identifying the path associated with the object.
@@ -24,6 +24,16 @@ class ConversionTest < ActiveModel::TestCase
assert_equal "1", Contact.new(:id => 1).to_param
end
+ test "to_param returns nil if to_key is nil" do
+ klass = Class.new(Contact) do
+ def persisted?
+ true
+ end
+ end
+
+ assert_nil klass.new.to_param
+ end
+
test "to_partial_path default implementation returns a string giving a relative path" do
assert_equal "contacts/contact", Contact.new.to_partial_path
assert_equal "helicopters/helicopter", Helicopter.new.to_partial_path,

0 comments on commit 98e2ae9

Please sign in to comment.