Javier Valencia
Javier Valencia

Reputation: 695

How to KISS and smart this method

I have an action in my RoR application, and it calls a different script depending on the user running it.

 def index

 @user = User.find(session[:user_id], :include => [ :balances, :links, :comments ])

 render :file => "#{RAILS_ROOT}/app/views/user/index_#{@user.class.to_s.downcase}.html.erb"

  end

How to make the call to render a more elegant and simple?

Upvotes: 0

Views: 269

Answers (2)

Chris Heald
Chris Heald

Reputation: 62708

Try:

render :template => "user/index_%s" % @user.class.to_s.downcase

Upvotes: 4

jordinl
jordinl

Reputation: 5239

You can make it a partial (index_whatever.html.erb --> _index_whatever.html.erb) and it would look like this:

def index
  @user = User.find(session[:user_id], :include => [ :balances, :links, :comments ])
  render :partial => "index_#{@user.class.to_s.downcase}"
end

Also, what I would do is add a method in the user model, like this:

def view
  "index_#{class.to_s.downcase}"
end

So your index action would be:

def index
  @user = User.find(session[:user_id], :include => [ :balances, :links, :comments ])
  render :partial => @user.view
end

Upvotes: 1

Related Questions