How to transfer parameters from the controller to the template?

It seems that setting several instance variables in the controller action (method) causes problems in the template, only the first variable of the first instance is passed to the template. Is there a way to pass multiple variables to a template? Thank you And why, in the Ruby perspective, does a template access instance variables in action?

+6
ruby-on-rails
source share
2 answers

You can also look at the options: locals for rendering. Which accepts the hash, so the keys are characters that map to local variable names in your template, and the values ​​are the values ​​for setting these local variables.

Example:

render "show", :locals => {:user => User.first, :some_other_variable => "Value"} 

and this template

 User ID: <%= user.id %><br> Some Other Variable: <%=some_other_variable%> 

will produce:

 User ID: 1<br> Some Other Variable: Value 

When you reuse partial elements for multiple controllers. Setting local variables with the: locals option is simpler and much more DRY than using instance variables.

+4
source share

You should have no problem setting multiple instance variables. For example:

 class CarsController < ApplicationController def show @car = Car.find(:first) @category = Category.find(:first) end end 

will allow you to access both @car and @category in cars / show.html.erb

The reason it works has nothing to do with ruby, but some kind of magic is built into the rails. Rails automatically makes any instance variable set in the controller action available for the corresponding view.

+4
source share

All Articles