01 August 2008

ActiveRecord find method is quite flexible

Every day, a new discovery about a Rails feature :-)

It sounds like the "find" methods is not too picky about its parameter, if given a string instead of an integer, it will the find the record anyway. I wonder if the author of this code knew about it ...

Event.find("7476-taranna")
=> #Event id: 7476, name: "TarannĂ ", place_id: 484, ...

Update:
After Marius' comment, I googled a bit and found a post by Obie Fernandez which explains the whole thing in details ...

2 comments:

marius said...

Actually, this functionality is often used for creating somewhat search engine friendly URLs. If you define a custom to_param method in an ActiveRecord::Base subclass, like this:


def to_param
"#{id}-#{title.gsub(/\s/,"_")}"
end

your model will emit something like
123-we_have_a_winner

when used with link_to etc. But active record will call to_i on this parameter before using it in a find call, which leaves it up to String#to_i to return the correct identifier. And "123-we_have_a_winner".to_i returns ... 123

Jean-Michel said...

The author of the Model had added a to_param method which behaves exactly like Marius said ...