诗歌rails之model name in url

关键字: Rails url
设计更利于搜索的url是SEO的一个要点,我们来看看怎样将http://localhost/products/6转化成
http://localhost/products/6-gallon-of-milk或者http://localhost/products/gallon-of-milk
对第一种url,首先添加permalink字段:
ruby代码
  1. create_table "products", :force => true do |t|  
  2.   t.column "name",        :string  
  3.   t.column "price",       :float  
  4.   t.column "description", :text  
  5.   t.column "permalink",   :string  
  6. end  
页面中的链接改为:
ruby代码
  1. <%= link_to h(product.name), :action => 'show', :id => product %>  
覆盖Product类的to_param方法:
ruby代码
  1. def to_param  
  2.   "#{id}-#{permalink}"  
  3. end  
controller也得改:
ruby代码
  1. def show  
  2.   @product = Product.find(params[:id])  
  3. end  
但是第一种url在#{id}后的#{permalink}值可以任意修改,因为controller实际上还是根据前面的id来查询Product的
posted @ 2009-07-10 11:27  麦飞  阅读(497)  评论(0编辑  收藏  举报