Baylor Rae'
Baylor Rae'

Reputation: 4010

Rails 3.2 - Custom render method returns source of partial within an array

I have the following method in my ApplicationController so that I can load unique views depending on the user's privileges. It works fine when I call it within the controller, but when I specify a partial I get the partial's source instead of it rendering it.

class ApplicationController < ActionController::Base
  include ControllerAuthentication

  private

  def render(*args)
    options = args.extract_options!
    render_options = _normalize_render(*args)

    location = logged_in? && current_user.is_admin? ? "admin" : "client"

    options[:template] = "/#{location}/#{params[:controller]}/#{render_options[:action] || params[:action]}"

    if options[:partial]
      options[:partial] = "#{location}/#{params[:controller]}/#{options[:partial]}"
    end

    super(*(args << options))
  end
  helper_method :render

end

<%= render partial: "form" %> outputs something like this on the page.

["<form ...>...</form>"]

I've been reading through the source of the render method, but I haven't pinpointed what is causing this. What do I need to change so I can render the partial correctly.

Upvotes: 0

Views: 358

Answers (1)

vvlad
vvlad

Reputation: 579

The render method from AbstractController::Rendering has a different behaviour from the one defined in ActionView::Helpers. The fact you're getting an array is normal since the rack stack expects and Enumerable for the body.

With helper_method :render your overriding the implementation of the render method defined in ActionView::Helpers.

I think it would be better to namespace your controllers and extract the common functionality (if any) in a module or a controller that will be used as a base controller for the specific implementation for each role.

for example you could have something like:

namespace :admin do
  resources :posts
end

namespace :client do
  resources :posts
end

the controllers for this will be located @

app/controllers/admin/posts_controller.rb
app/controllers/client/posts_controller.rb

and the views

app/views/admin/posts/...
app/views/client/posts/...

So basically you'll gonna achieve the same effect but in a more railish manner, and this solves also the view problem.

Upvotes: 1

Related Questions