Permalinks with Ruby on Rails (dynamic routes)

2019-01-17 18:45发布

问题:

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

the user should be able to set the page name, eg. "test-article" (that should be available via /posts/test-article) - how would I realize this in the rails applications and the routing file?

回答1:

Modifying the to_param method in the Model indeed is required/convenient, like the others said already:

def to_param
  pagename.parameterize
end

But in order to find the posts you also need to change the Controller, since the default Post.find methods searches for ID and not pagename. For the show action you'd need something like this:

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

Same goes for the other action methods.

You routing rules can stay the same as for regular routes with an ID number.



回答2:

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



回答3:

I personally prefer to do it this way:

Put the following in your Post model (stick it at the bottom before the closing 'end' tag)

def to_param
  permalink
end

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

That's it. You don't need to change any of the find_by methods. This gives you URL's of the form "123-title-of-post".



回答4:

You can use the friendly_id gem. There are no special controller changes required. Simple add an attribute for example slug to your model..for more details check out the github repo of the gem.



回答5:

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



回答6:

You should have seolink or permalink attribute in pages' or posts' objects. Then you'd just use to_param method for your post or page model that would return that attribute.

to_param method is used in *_path methods when you pass them an object.

So if your post has title "foo bar" and seolink "baz-quux", you define a to_param method in model like this:

def to_param
  seolink
end

Then when you do something like post_path(@post) you'll get the /posts/baz-quux or any other relevant url that you have configured in config/routes.rb file (my example applies to resourceful urls). In the show action of your controller you'll just have to find_by_seolink instead of find[_by_id].