I'm almost done a project and only now am I implementing friendly
URLs. I'm using the method from "Simply Rails 2" by Patrick Lenz.
This involves the following addition to the model:
So every time a url is generated it creates a friendly URL.
I'm now having trouble with my controllers though.
if i use @item = Item.find(params[:id]) # Everything works fine.
I have in many spots magick find methods like
@item = Item.find_by_id(params[:id])
@item = Item.find_by_associated_model_id(params[:id])
Which will actually attempt to find the entire friendly URL string as
an ID in the database.
I can fix the problem with
@item = Item.find_by_associated_model_id(params[:id].to_i)
As this will strip the appended string. But I feel theres probably
something I'm missing / a more graceful way.
I don't think there is... find() converts it's argument to an integer. The other's do not. Might be an interesting patch since you should be able to determine what the underlying data type is and then cast it.
And while you're to_param is fine, you might check out http://github.com/rsl/stringex. It does something similar, but is has some more smarts under the hood (expanding symbols, etc.). No affiliation, just like it.
# A simple prelude
"simple English".to_url => "simple-english"
"it's nothing at all".to_url => "its-nothing-at-all"
"rock & roll".to_url => "rock-and-roll"
# Let's show off
"$12 worth of Ruby power".to_url => "12-dollars-worth-of-ruby-power"
"10% off if you act now".to_url => "10-percent-off-if-you-act-now"
# You don't even wanna trust Iconv for this next part
"kick it en Français".to_url => "kick-it-en-francais"
"rock it Español style".to_url => "rock-it-espanol-style"
"tell your readers 你好".to_url => "tell-your-readers-ni-hao"
Hey thanks for the reply, http://github.com/rsl/stringex does look
very handy I'll keep it in mind in the future.
Just out of curiosity what did you mean by "Might be an interesting
patch since you
should be able to determine what the underlying data type is and
as in maybe I should write a helper that checks the data type and
passed it to the find ? or returns the desired results... hmmm I
suppose i do have some options.
Thanks for the reply!