Permalink with Ruby on Rails (dynamic routes)

I am currently developing a blogging system with Ruby on Rails and I want the user to define their "permalinks" for static pages or blog posts, which means:

the user should be able to set the page name, for example. "test article" (which should be available through / posts / test -article) - how would I understand this in rails applications and the routing file?

+4
source share
6 answers

Modification of the to_param method in the Model is really required / convenient, like the others already said:

 def to_param pagename.parameterize end 

But in order to find messages, you also need to change the controller, since the Post.find methods by default look for the identifier, not pagename. For the show action, you need something like this:

 def show @post = Post.where(:pagename => params[:id]).first end 

The same applies to other methods of action.

Routing rules can remain the same as for regular routes with an identification number.

+3
source

for friendly permalinks you can use gem 'has_permalink'. For more information http://haspermalink.org

+4
source

I personally prefer to do this as follows:

Put the following in the Post model (hold it down until the close tag)

 def to_param permalink end def permalink "#{id}-#{title.parameterize}" end 

What is it. You do not need to change any find_by methods. This gives you the URL of the form "123-title-of-post".

+2
source

You can use the friendly_id gem. No special controller changes are required. Just add an attribute like slug to your model. For more details check out the github repo gem.

+2
source

# 63 and # 117 episodes of railscasts can help you. Also check out the resources there.

+1
source

You must have the seolink or permalink attribute in the page or post objects. Then you simply use the to_param method for your publication or page model that will return this attribute.

to_param method is used in *_path methods when passing an object to them.

So, if your message has the header "foo bar" and seolink "baz-quux", you define the to_param method in the model as follows:

 def to_param seolink end 

Then, when you do something like post_path(@post) , you will get /posts/baz-quux or any other relevant URL that you configured in config/routes.rb (my example refers to resourceful URLs ) In your show action of your controller, you just need to find_by_seolink instead of find[_by_id] .

0
source

All Articles