SEO friendly URLs in RoR

你。 提交于 2019-11-28 09:31:27

Check out friendly_id gem. It is exactly what you need.

Define your to_param in the model:

class album
    def to_param
        "#{id}-#{album-name.parameterize}"
     end
end

Now you can use

<%= link_to album.album_name, album %>

to create the link to the seo path

Then in your controller:

Album.find(params[:id])

will call to_i -> so you get the Topic.find(2133) or whatever.

This will result in urls of the form: "/album/2-dark-side-of-the-moon" which although not exactly what was asked for has advantages - The id is used to find the album - which is unique, when the name might not be.

The parameterize method "Replaces special characters in a string so that it may be used as part of a ‘pretty’ URL" - http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-parameterize

If you want to display URL in browser as app/albums/lets-talk but POST params as album_id => 1, for shopping cart addition etc.

In your album model:

# PRODUCT MODEL
 before_create do
   self.navigation = album_name.downcase.gsub(" ", "-")  
  end

def to_param
    [id, album_name.parameterize].join("-")
end

Now you can

@album = Album.find_by_navigation(params[:id])

and

album = Album.find(params[:album_id])

It seems like you whant to override :id parameter to :name parameter. This case described in this article.

class User < ActiveRecord::Base
  def to_param  # overridden
    name
  end
end

user = User.find_by_name('Phusion')
link_to 'Show', user_path(user)  # => <a href="/users/Phusion">Show</a>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!