2
votes

My question is how would one go about in rails to create a nested static page? I'm a newb, "self-taught" to Ruby on Rails and have been searching for this answer. Any help would be appreciated, Thank You.

For example:

  • Site root
    --- Ships (http://wwww.example.com/ships)
    ------ Types of Ships (http://wwww.example.com/ships/types-of-ships)


Directory Structure:

app/view/static/ships/types-of-ships


Current Static Controller

class StaticController < ApplicationController def show render params[:pages] end end


Routes

get "/:pages" => "static#show"

1
can we see your #show action in StaticController? I would assume you could just change your route to get "/ships/:pages" => "static#show". The only thing I would caution is that if you use that route, what happens if someone tries to go to www.site.com/ships/asdfasdsa ? there won't be a view for it. maybe consider specifying the pages directly or adding a catch-all route at the end of your routes file.jstim
def show render params[:pages] endlyndze

1 Answers

4
votes

If you want to create static pages in a Rails app, there are a few resources I would check out.

The last link above is really the go-to for static pages, so I'll address the more specific part of your question regarding nesting.

If you want to map a url to a controller action (and a view), you can simply add it into your routes file. And if you want that to be namespaced, you can just add the namespace in front of the :pages symbol that will pass along the specific ship name.

get "ships/:pages" => "static#show"
# so going to www.example.com/ships/titanic
# will show your app/view/static/ships/titanic.html.erb page

Alternative: Gem for Static Pages

Alternatively, thoughtbot created a gem called high_voltage that handles some of the setup. I haven't used it, but it may be worth looking at.

Warning on Routes

With the routes entry you have though, I would caution you that it may have unintended consequences, because if someone enters a route that doesn't match a file you have, it will throw an error.

If you go this route, I would suggest reading up on a catch-all route. You could:

Or whatever else you think would be most helpful to your users.

Once again, there are caveats, because this will catch all errors and ignore other items like rails engines (from what I understand).

Alternative Architecture

I can modify this section based on your answers in the comments, but it seems like you want to add a large number of pages in this category.

Since these are all ships and I assume they have similar data points around each one, you could save this information in the database and just create a Ship scaffold to manage it like a normal Rails project.

This would allow you to:

  • store as many ships as you wanted
  • have a single templated #show page
    • this keeps your views DRY and makes changing the template that much easier