Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variable to render in controller method in Rails

I am trying to pass a variable to render like this:

def monitor
  @peripheries = Periphery.where('periphery_type_name=?','monitor')
  render 'index', type: 'Monitor'
end

Here i want to use 'type' variable inside index view which looks like that:

<%= render 'some_partial', periphery_type: type %>

which also render something. But i want to use that 'type' variable

like image 204
yerassyl Avatar asked Jun 07 '15 12:06

yerassyl


3 Answers

There are two ways to pass variables between the controller and views:

Instance variables

def monitor
  @peripheries = Periphery.where('periphery_type_name=?','monitor')
  @type = 'Monitor'
  render 'index'
end
 

Rails will export any of the instance variables belonging to the controller to the view context. So you can call @type in the view or any partial.

Locals

def monitor
  @peripheries = Periphery.where('periphery_type_name=?','monitor')
  render 'index', locals: { type: 'Monitor' }
end

Note that you need to pass a hash to the locals option. You also need to pass the local variable to partial views:

<%= render 'some_partial', locals: { periphery_type: type } %>

Using locals is often a good idea since it encourages decoupling and can make your partials more reusable.

like image 162
max Avatar answered Oct 13 '22 13:10

max


You can use redirect_to some_path(params: params)

like image 28
Marìa Angelica Avatar answered Oct 13 '22 13:10

Marìa Angelica


In the monitor method, you can pass the type variable to the index view e.g.

def monitor
  @type = 'monitor'
  @peripheries = Periphery.where('periphery_type_name = ?', @type)
  render 'index'
end

and in your view

<%= render 'some_partial', locals: {periphery_type: @type}

(Note this is not a good way to set up the type variable, I would need a better understanding of the class to suggest how to set that variable.)

like image 22
margo Avatar answered Oct 13 '22 12:10

margo