Welcome to Working With Rails

 

Discussion Forums

Discuss all things Ruby on Rails with perhaps the web's most vibrant group of Ruby on Rails enthusiasts.
One url with multiple controllers
5 Posts
One url with multiple controllers

Lets say that I want to have one url that can map to two different controllers. For example /posts could map to controller 'public/ posts' or to the controller 'admin/posts' based on whether or not the user has logged in. This isn't a great example because I could just use the url '/admin/posts', but in my scenario the url has to be the same.

I was hoping to use a before_filter to either render one action or the other. It looks like render_component would have let me accomplish this, but it has been deprecated.

Thanks! Tom

Hi Tom

Why isn't it possible to use the same controller and conditional views?

I mean, wouldn't it be easier and more standard to use helpers and conditions within views than calling a different controller?

If you need different methods to be executed depending on user roles, you could call the same controller and define it like this one:

class Posts < ApplicationController

def index

#do common stuff

if user.role == 'admin'
  admin_index
else
  user_index
end

end

private def admin_index

#admin methods to be executed

end

def user_index

#user methods

end

end

Remember to test your views, in case you call any variable that's not defined in both actions.

Hope it helps.

Francisco, that would definitely work in some cases, but in mine I really need to have a separate controller when certain conditions are meant. It would be great if the :conditions on the route maps allowed you more options than just :method!

you could redirect to admin/posts using a before_filter.

something like

redirect_to admin_post_path and return false if current_user.admin

The routes shouldn't really have any logic in them other than routing logic, e.g checking what path information was supplied and then redirecting you to the appropriate controller / action

bq. redirect_to admin_post_path and return false if current_user.admin

Omar, that was a gorgeous example of Rails code and is a perfect example of why I love the language. Just a side note. ;)

5 Posts
Login to add your message