关键字: 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的

相关文章:

  • 2022-12-23
  • 2022-01-08
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-08-12
  • 2022-12-23
  • 2021-05-30
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案