It seems that setting multiple instance variables in a controller's action (method) causes problems in the template, only the very first instance variable got passed to the template. Is there any way to pass multiple variables to the template? Thanks! And why, in Ruby's perspective, does the template get access to the instance variables in an action?
You might also want to look into the :locals option of render. Which accepts a hash such that keys are symbols that map to local variable names in your template, and the values are the values to set those local variables to.
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're reusing partials across multiple controllers. Setting local variables with the :locals option is simpler and much more DRY than using instance variables.
you shouldn't have any 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 this works is nothing inherent to ruby, but some magic built into rails. Rails automatically makes any instance variable set in a controller action available to the corresponding view.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With