Ask A Question

Notifications

You’re not receiving notifications from this thread.

How is routing done with a conditional in url?

Matt Taylor asked in Rails

Not sure the correct words to ask the question are. Here is an example from what I have seen: http://www.gorails.com/series/1?old_content=true

So say Chris re-did some of the screencasts,and now he had two versions of the view(content). What is the way like the example url above that you could view the old view(content) by using ?old_content=true. How would that be set up in routes or would that be in the controller?

I hope this question makes sense.

Thanks for the help.

Edit: I just saw a real example here on gorails where it is saying ?autoplay=1

Reply

Hey Matt,

?old_content=true is a param that's being passed to the controller action possibly located in controllers/series_controller.rb. Inside, let's say the show action, there would be something like old_content = params[:old_content] which would be populated with it's value, so in this case, true.

Now Chris can do all sorts of things with this info...

def show
  old_content = params[:old_content]

    if old_content == true
      return something special if it's supposed to be the old content
    else 
      return soemthing else when old_content is false or not present at all
    end
end

You can also chain them: ?old_content=true&autoplay=1&this_is_cool=true

and access like:

old_content = params[:old_content]
autoplay = params[:autoplay]
this_is_cool = params[:this_is_cool]

if this_is_cool
  puts "you rock!"
end
Reply

Thanks Jacob. So in the example of his autoplay=1 is he hardcoding that onto the end of the url path, or how is that getting added to the params hash?

Thanks

Reply

In a link, you can do something like

<%= link_to "Put a param", show_series_path(autoplay: 1) %>

to pass the param. You can also manually type it when you're testing in your own application.

Reply

Jacob is exactly right. :D

And just a quick note: generally you use these url params to do filtering (like pagination) or sorting or you'd use them to turn on and off simple features like autoplaying of videos like you see on here.

Then sometimes it's nicer to have a full path dedicated to a section to designate it's importance so I'll tend to do that for things like forum categories. Rather than just saying /forum?category=rails I've got /forum/category/databases to kind of denote that it's a dedicated page.

It's late so I don't know if I'm explaining that bit well, so here's a stack overflow post that describes the same thing: http://webmasters.stackexchange.com/a/15394

Reply

Thanks guys.. This clears it up for me!!

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 86,796+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.