Created
July 18, 2012 11:50
-
-
Save deepak/3135755 to your computer and use it in GitHub Desktop.
ActiveRecord#find needs an id even when to_param/from_param has an override
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# couple of problems | |
# 1. the name to_param is not domain specific. it is to uniquely specify | |
# the record in urls and such | |
# 2. find does not work seamlessly with to_param | |
# read comments at http://apidock.com/rails/ActiveRecord/Base/to_param | |
class PaymentOld < ActiveRecord::Base | |
attr_accessible :amount, :desc | |
def to_param | |
desc | |
end | |
def self.from_param(name) | |
find_by_desc name | |
end | |
end | |
class Payment < ActiveRecord::Base | |
attr_accessible :amount, :desc | |
def to_param | |
"#{id}-desc" | |
end | |
def self.from_param(name) | |
find_by_desc name.split('-').second | |
end | |
end | |
p = PaymentOld.create! amount: 100, desc: "first" | |
p.to_param #first | |
PaymentOld.from_param(p.to_param) #got it | |
PaymentOld.find(p.to_param) #fails | |
# ActiveRecord::RecordNotFound: Couldn't find PaymentOld with id=first | |
# read comments at http://apidock.com/rails/ActiveRecord/Base/to_param | |
# but if to_param appends id to to_param then it works | |
# as find searches for an id at the start and ignores all | |
p = Payment.create! amount: 100, desc: "first" | |
p.to_param #1-first Note that 'id' is appended | |
Payment.from_param(p.to_param) #got it | |
Payment.find(p.to_param) # success | |
param = p.to_param | |
p.desc = "second" | |
p.save! | |
#still works even though the record does not have that desc | |
Payment.find(param) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
created an issue at, rails/rails#7092