Search code examples
ruby-on-railsrenderrenderpartial

Rails rendering a different view depending on the controller


I have a tab navigation page in my rails app which is shared across all of my views. Inside I have a small text area which should change depending on the page that the user is on.

Currently I am doing this by adding a variable to the controller and using it in the render partial path, like so:

class Myapp::WebsitesController < MyappController
  def set_up
    @page = 'websites/left_text_info'
  end 

and then in my partial:

<%= render :partial => @page %>

This works but it doesn't feel like the best 'ruby' way of doing things. Can anyone advise on a better way of doing this?

Thanks


Solution

  • You can use controller_name helper method directly in your view and skip the controller part:

    <%= render "#{controller_name}/left_text_info" %>
    

    Or if the only thing that change is the content of the textarea, then perhaps the best way is to define a helper method that returns only the content for it, so you don't need multiple partial files that are very similar.

    module ApplicationHelper
      def text_area_content
        case controller_name
        when "users"
          "content for users"
        when "articles"
          "content for articles"
        else
          "other content"
        end
      end
    end