1

How can I render an action of a controller which is in a different namespace?

For example, if I have a login controller in a Webapp namespace Webapp::LoginController and I want to render the index action (not a partial!) in an events controller in the API namespace API::EventsController if the user is logged in:

class Webapp::LoginController < ApplicationController
  include Webapp::LoginHelper
  def index
    render 'events/index' if logged_in? # events#index is in the API namespace
   end
end

Is this even possible? I see the answer being no because of potential conflicts with subdomains and paths, depending on how the routes are defined.

I know I could redirect to the page I'd like with

redirect_to api_events_url

but this will create a new request which I don't necessarily want.

Tobias Geisler
  • 679
  • 7
  • 13
  • have you tried this `render action: 'events/index'` – Amit Sharma Jun 10 '15 at 19:35
  • Yes, this won't work, as this refers to actions in the same controller. But you gave me the idea to a different approach, trying to render the file on the path (`render "/vagrant/app/views/api/events/index"`). Interestingly, it won't find the file there: `Missing template app/views/api/events/index with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in: * "/vagrant/app/views" ` – Tobias Geisler Jun 10 '15 at 19:54

1 Answers1

3

This worked for me

render 'api/events/index'
Serafim221
  • 46
  • 4
  • This works, thank you! I originally thought this would render a partial, since it threw an undefined method error on one. What I missed was that a partial used by the template I called required some variables to be set by the events controller, hence the error on the partial. For future reference, [this question](http://stackoverflow.com/questions/5767222/rails-call-another-controller-action-from-a-controller) lines out some DRY ways to reuse the API Controller code (i like apneadiving's answer) - which is not recommended since it neglects the MVC concept. Other possibility: helper methods. – Tobias Geisler Jun 10 '15 at 20:28