在某些书籍中,建议将to_param更改为
class Story < ActiveRecord::Base
def to_param
"#{id}-#{name.gsub(/\W/, '-').downcase}"
end
end
所以URL是
http://www.mysite.com/stories/1-css-technique-blog
而不是
http://www.mysite.com/stories/1
这样URL对搜索引擎更友好。
所以可能to_param()不需要被Rails的其他部分使用,而更改它可能会有任何副作用?或者可能唯一的目的是构建链接的URL?
另一件事是,它不需要限制URL的长度小于2K吗——如果超过2K,它会扼杀IE吗?或者可能超过2K的部分被IE忽略了,因此URL仍然有效。最好是限制在30或40个字符以内,或者是一些使URL不太长的字符。
此外,
ri
收件人参数:
class User < ActiveRecord::Base
def to_param # overridden
name
end
end
如果“to”参数是那样更改的,那么链接实际上将不起作用,因为
http://www.mysite.com/stories/1-css-technology-blog
会工作,但
http://www.mysite.com/stories/css-technique-blog
将不起作用,因为缺少ID。是否有其他方法可以将to_param方法更改为?
更新:
再想想,也许
http://www.mysite.com/stories/css-technology-blog
如果有许多标题相似的网页,效果就不好了。但是然后
http://www.mysite.com/user/johnchan
会工作。会不会是参数[:id]是“johnchan”?那么我们就用
user = User.find_by_login_name(params[:id])
获取用户。所以这取决于我们如何使用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"