原创作者: hideto   阅读:1055次   评论:0条   更新时间:2011-05-26    
设计更利于搜索的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必需唯一
评论 共 0 条 请登录后发表评论

发表评论

您还没有登录,请您登录后再发表评论

文章信息

Global site tag (gtag.js) - Google Analytics