Andrey Drozdov Andrey Drozdov - 1 year ago 95
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

resources :posts
. And right now - link to created post look like:
(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
. It must generate, for example post theme.

For start, we must create
column in Posts table. And make it to generate something like that: = @post.theme.parameterize.underscore

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

And the next problem is: "How to replace

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

Answer Source

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

def to_param

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

def find_post

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download