Routing without the model name

2019-07-17 15:59发布

问题:

Using this question and railscast 63 I've got my articles routed to articles/article_permalink.

I'd like them to be accessible without the model name in the url so my-domain.com/article_permalink routes directly to the article. I'd only want this to happen on the show action. Is this possible?

回答1:

I think you need something like ...

(in routes.rb)

 match '/:id' => 'articles#show', :via => 'get'

(needs to be last, or towards the end of the routes as it can match requests intended for other routes)

To change the article_path(...) helpers, "as" might help: http://guides.rubyonrails.org/routing.html#overriding-the-named-helpers

Or you can add a helper for that specific path.



回答2:

If I understand your question, you want the model tied to the route "articles/article_permalink" to be dynamic based upon which is article is selected from a list?

Would you be open to appending a model ID to the end of the URL as a query string? A more complicated approach would be to have your links POST, with the model ID as a hidden input field. Your controller could determine if it was accessed via get/post, and handle it accordingly, but that doesn't feel right.

Regardless, when the controller action is fired up based upon a request to "articles/article_permalink", it has to know which model to fetch. With HTTP being stateless, something has to be passed in. You could get fancy and write JavaScript to fire one AJAX call, set a session var, and then fire the GET, but that's messy.

I hope I understood the question...