Dynelight
Dynelight

Reputation: 2162

Setting optional parameters for Ruby on Rails' root on routes.rb

I'm using a static_pages controller in order to serve all my static page content. I want to be able to pass parameters to this static page content in order to open several modal boxes for login and message popups.

root 'static_pages#home'

How can I do this?

Upvotes: 4

Views: 1213

Answers (2)

Brian Davis
Brian Davis

Reputation: 357

One way to do it which does used routes.rb is this:

 # config/routes.rb
 get 'posts/:id(/:opt1(/:opt2(/:opt3)))' => 'posts#show'

Then debug the params in the view

 # app/views/posts/show.html.erb
 <%= params %>

If the URL is posts/1/A/B/C This will show:

 {"controller"=>"posts", "action"=>"show", "id"=>"1"
  "opt1"=>"A", "opt2"=>"B", "opt3"=>"C"}

The parentheses in the route are optional and treated as params to the non-parenthesis part of the route.

Upvotes: 3

NM Pennypacker
NM Pennypacker

Reputation: 6942

You can do it in the view with Javascript if certain params exist.

For example, in home.html.erb

<% if params[:your_param] == true %>
  <script type="text/javascript">
    // fire modal
  </script>
<% end %>

And then just add your param to the query string:

http://www.yoursite.com/?your_param=true

No need to modify the routes file. The modals are view-related, so why not keep the logic in the view?

As far as your comment goes about a conditional redirect, sounds like a job for the controller. You have access to params in the controller as well, so you can redirect as needed depending on the params passed to the action.

Upvotes: 3

Related Questions