Rails宝典之第六十三式: model name in url

设计更利于搜索的url是SEO的一个要点,我们来看看怎样将 http://localhost/products/6转化成
http://localhost/products/6-gallon-of-milk或者 http://localhost/products/gallon-of-milk

对第一种url,首先添加permalink字段:
create_table "products", :force => true do |t|
  t.column "name",        :string
  t.column "price",       :float
  t.column "description", :text
  t.column "permalink",   :string
end

页面中的链接改为:
<%= link_to h(product.name), :action => 'show', :id => product %>

覆盖Product类的to_param方法:
def to_param
  "#{id}-#{permalink}"
end

controller也得改:
def show
  @product = Product.find(params[:id])
end

但是第一种url在#{id}后的#{permalink}值可以任意修改,因为controller实际上还是根据前面的id来查询Product的

第二种url:
覆盖Product类的to_param方法:
def to_param
  permalink
end

controller也得改:
def show
  @product = Product.find_by_permalink(params[:id])
end

第二种url比第一种安全,不过限制是permalink必需唯一

你可能感兴趣的:(Rails)