Andrey Drozdov Andrey Drozdov - 3 months ago 7
Ruby Question

Rails, how to change automatic generated link

I have a RoR app. And in app users can create posts. I've connected Posts table in my

routes.rb
via
resources :posts
. And right now - link to created post look like:
http://mysitename.com/posts/1
(where 1 is post number).

What i want to do, is to make rails generate link to post. So users didn't see how much posts I have in my DB. And as result it must look like
http://mysitename.com/post/generatedlink
. It must generate, for example post theme.

For start, we must create
link
column in Posts table. And make it to generate something like that:

@post.link = @post.theme.parameterize.underscore


But I don't understand, where to put this code.

And the next problem is: "How to replace
post/1
for
@post.link
?"

Hope, I make my self clear. If you'll say I can provide information, what is needed to resolve my question.

Answer

The technique is referred to as slugifying and you need to do three things...

(1) create a new field called slug in your posts table.

(2) add this code to your Post model...

after_validation :generate_slug

def generate_slug
  self.slug = theme.parameterize.underscore
end

def to_param
  slug
end

(3) finally, in your controllers where you have find_post methods, rewrite it to be...

def find_post
  post.find_by_slug(params[:id])
end

The to_param method in the model is how things like post_path(@post) build the url... the to_param if not replaced substituted the id field but by writing your own to_param method you can ensure that the slug field is substituted instead.