On Jan 27, 2010, at 2:39 AM, brianp wrote:

Hey,

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:

        def to_param
                "#{id}-#{name}".gsub(/\W/, '-').downcase
        end

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])
or
@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"

--
You received this message because you are subscribed to the Google Groups "Ruby on 
Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to