r2 - 02 Sep 2007 - 17:49:42 - HecPeAreYou are here: TWiki >  Rails Web > RailsSC > ModelNameInURL63RSC

63 Model Name In URL

By default, Rails uses the model's id in the URL. What if you want to use the name of the model instead? You can change this behavior by overriding the to_param method in the model. Watch this episode for details.

link

Cambiamos en index.rhtml

product_path(product)

por

...

y en product.rb añadimos:

def to_param
  "#{id}-#{permalink}"
end
Y en ... usamos Product.find(params[:id].to_i). El método to_i se queda con los carácteres numéricos.

Pero si no queremos el id:

def to_param
  permalink #o el campo que queramos
end
y cambiamos los find(params[:id]) por find_by_permalink(params[:id])

Aunq es más lento.

-- HecPeAre - 18 Aug 2007

Edit | Attach | Printable | Raw View | Backlinks: Web, All Webs | History: r2 < r1 | More topic actions
 
Powered by TWiki

This site is powered by the TWiki collaboration platformCopyright © by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback