Hrishikesh Sardar
Hrishikesh Sardar

Reputation: 2917

Is code reuse possible in this scenario?

I have a Index page which shows data for current_user only, and I made another page which shows the same data fields and same format as of index page but not for current_user but after querying for some other column, in this case is it possible to reuse the code of index and using some condition in the controller to pass the object variable different in each case ?

Thanks in advance

Upvotes: 0

Views: 96

Answers (2)

Billy Chan
Billy Chan

Reputation: 24815

Suppose the controller is FoosController and the action of index page for current_user is #bar, then your controller may look like this

class FoosController < ApplicationController
  def bar
    @user = current_user
  end

To reuse the template, you can make a separate partial template say app/views/foos/_index.html.erb.

Then, in app/views/foos/bar.html.erb

<%= render partial: '_index', locals: { user: @user }

To reuse the partial template in another action, you just need to call the partial in another template, feed it with different instance variable.

Upvotes: 1

Brad Werth
Brad Werth

Reputation: 17647

You bet - @user = params[:user_id] ? User.find( params[:user_id] ) : current_user

Upvotes: 1

Related Questions