设计更利于搜索的url是SEO的一个要点,我们来看看怎样将[url]http://localhost/products/6[/url]转化成
[url]http://localhost/products/6-gallon-of-milk[/url]或者[url]http://localhost/products/gallon-of-milk[/url]
对第一种url,首先添加permalink字段:
[code]
create_table "products", :force => true do |t|
t.column "name", :string
t.column "price", :float
t.column "description", :text
t.column "permalink", :string
end
[/code]
页面中的链接改为:
[code]
<%= link_to h(product.name), :action => 'show', :id => product %>
[/code]
覆盖Product类的to_param方法:
[code]
def to_param
"#{id}-#{permalink}"
end
[/code]
controller也得改:
[code]
def show
@product = Product.find(params[:id])
end
[/code]
但是第一种url在#{id}后的#{permalink}值可以任意修改,因为controller实际上还是根据前面的id来查询Product的
第二种url:
覆盖Product类的to_param方法:
[code]
def to_param
permalink
end
[/code]
controller也得改:
[code]
def show
@product = Product.find_by_permalink(params[:id])
end
[/code]
第二种url比第一种安全,不过限制是permalink必需唯一
[url]http://localhost/products/6-gallon-of-milk[/url]或者[url]http://localhost/products/gallon-of-milk[/url]
对第一种url,首先添加permalink字段:
[code]
create_table "products", :force => true do |t|
t.column "name", :string
t.column "price", :float
t.column "description", :text
t.column "permalink", :string
end
[/code]
页面中的链接改为:
[code]
<%= link_to h(product.name), :action => 'show', :id => product %>
[/code]
覆盖Product类的to_param方法:
[code]
def to_param
"#{id}-#{permalink}"
end
[/code]
controller也得改:
[code]
def show
@product = Product.find(params[:id])
end
[/code]
但是第一种url在#{id}后的#{permalink}值可以任意修改,因为controller实际上还是根据前面的id来查询Product的
第二种url:
覆盖Product类的to_param方法:
[code]
def to_param
permalink
end
[/code]
controller也得改:
[code]
def show
@product = Product.find_by_permalink(params[:id])
end
[/code]
第二种url比第一种安全,不过限制是permalink必需唯一