In some book, it is recommended that to_param is changed to
class Story < ActiveRecord::Base
def to_param
"#{id}-#{name.gsub(/\W/, '-').downcase}"
end
end
so that the URL is
http://www.mysite.com/stories/1-css-technique-blog
instead of
http://www.mysite.com/stories/1
so that the URL is more search engine friendly.
So probably to_param() doesn't need to be used by other parts of Rails that changing it may have any side effect? Or maybe the only purpose is to construct a URL for linking?
Another thing is, won't it require to limit the URL size to be less than 2k in length -- will it choke IE if it is more than 2k or maybe the part more than 2k is just ignored by IE and so the URL still works. It might be better to be limited to 30 or 40 characters or something that will make the URL not exceedingly long.
Also, the ri
doc of to_param:
class User < ActiveRecord::Base
def to_param # overridden
name
end
end
if to_param is changed like that, then the link actually won't work, as
http://www.mysite.com/stories/1-css-technique-blog
will work, but
http://www.mysite.com/stories/css-technique-blog
will not work as the ID is missing. Are there other ways to change the to_param method?
Update: on second thought, maybe
http://www.mysite.com/stories/css-technique-blog
won't work well if there are many webpages with similar title. but then
http://www.mysite.com/user/johnchan
will work. Will it be params[:id] being "johnchan"? So then we will use
user = User.find_by_login_name(params[:id])
to get the user. So it just depends on how we use the param on the URL.
C:\ror>ri ActiveRecord::Base#to_param
-------------------------------------------- ActiveRecord::Base#to_param
to_param()
------------------------------------------------------------------------
Returns a String, which Action Pack uses for constructing an URL to
this object. The default implementation returns this record's id as
a String, or nil if this record's unsaved.
For example, suppose that you have a User model, and that you have
a +map.resources :users+ route. Normally, +user_path+ will
construct a path with the user object's 'id' in it:
user = User.find_by_name('Phusion')
user_path(user) # => "/users/1"
You can override +to_param+ in your model to make +user_path+
construct a path using the user's name instead of the user's id:
class User < ActiveRecord::Base
def to_param # overridden
name
end
end
user = User.find_by_name('Phusion')
user_path(user) # => "/users/Phusion"