0

I'm sorry, my English is bad. Question: I have model Pages with columns title, description etc. I can create, change, destroy these pages. I can see the contents of the link mydomain/pages/1. I need for each page has been template and route, so I can see the content on the link, for example maydomain/contacts. How to do it? Help me please.

kouty
  • 320
  • 8
  • 17
yermocode
  • 17
  • 4

2 Answers2

0

One way to implement your own solution is to add this to your routes file:

get '/mydomain/:slug, to: 'pages#show'

This is a pretty general matcher, so add it to the bottom of your routes so it doesn't override others.

Then your controller show action will look something like:

def show
  @page = Page.find_by_slug(params[:slug])
end

This of course assumes you have a slug column on your Pages table.

n_i_c_k
  • 1,504
  • 10
  • 18
0

I'm assuming by "mydomain" you mean the root url of your site (e.g. myapp.example.com)

I'd suggest that you separate the problem into two parts:

  1. Use an attribute other than id to identify an item in the url
  2. Reduce the route so that the controller does not need to be specified.

For 1, have a look at this: Rails routes with :name instead of :id url parameters Note, that as @spickermann suggests friendly_id could be a good solution for you.

For 2, you will need to create a route without the controller name, and then specify the controller in the route definition. (See the Rails Routing Guide):

get ':param', to: :show, controller: 'pages'

For that to work, you will need to put it after (lower in routes.rb) so that it doesn't intefer with other routes. I'd also recommend adding a constraint to the route - to limit the wrong urls that could be routed to that rout.

Community
  • 1
  • 1
ReggieB
  • 8,100
  • 3
  • 38
  • 46