开发者

How to pass parameters from a controller to a template?

开发者 https://www.devze.com 2022-12-14 10:17 出处:网络
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

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? Tha开发者_如何学Gonks! 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消