将局部变量传递给嵌套部分

bkn*_*les 5 nested ruby-on-rails partial-views

我有一个页面,大致像这样呈现一个集合:

索引.html.haml

= render partial: 'cars_list', as: :this_car,  collection: @cars
Run Code Online (Sandbox Code Playgroud)

_cars_list.html.haml

编辑: _cars_list 有关于个别汽车的其他信息。

%h3 Look at these Cars!
%ul
  %li Something about this car
  %li car.description
%div
  = render partial: 'calendars/calendar_stuff', locals: {car: this_car}
Run Code Online (Sandbox Code Playgroud)

_calendar_stuff.html.haml

- if car.date == @date
  %div 
    = car.date
Run Code Online (Sandbox Code Playgroud)

_cars_contoller.rb

def index
  @cars = Car.all
  @date = params[:date] ? Date.parse(params[:date]) : Date.today
end
Run Code Online (Sandbox Code Playgroud)

在日历内容部分发生的事情是,this_car它总是汽车收藏中的第一辆车,即相同的日期被一遍又一遍地打印出来。

如果我将逻辑_calendar_stuff移入cars_list部分,则打印结果会按预期更改。

因此,似乎 Railsthis_car每次渲染部分时都没有将本地对象传递到嵌套部分中。

有谁知道为什么?

PS如果我用

@cars.each do |car|
  render 'cars_list', locals: {this_car: car}
end
Run Code Online (Sandbox Code Playgroud)

我得到了同样的行为。

Pau*_*nti -1

尝试这个重构,看看是否得到你想要的输出:

索引.html.haml

= render 'cars_list', collection: @cars, date: @date
Run Code Online (Sandbox Code Playgroud)

去掉关键字partial,并将实例变量作为局部变量传递@date,以将逻辑封装在局部变量中。这一点是我从Rails Best Practices中得到的。

_cars_list.html.haml

%h3 Look at these Cars!
%ul
  %li Something about this car
%div
  = render 'calendars/calendar_stuff', car: car, date: date
Run Code Online (Sandbox Code Playgroud)

@cars当您作为 a传入时collection,该部分将引用一个名为 的单数局部变量car,然后该变量可以与当前的局部变量一起传递到下一个部分date。由于正在渲染的部分位于与此处不同的位置(上方下方calendars/),partial因此此处明确需要关键字。

_calendar_stuff.html.haml

- if car.date == date
  %div 
    = car.date
Run Code Online (Sandbox Code Playgroud)

编辑

建议将调用移至collection_cars_list.html.haml 但这不适合该问题。

编辑2

如果您仍想将局部变量指定为 ,则这是上述代码的版本this_car,因此您将覆盖自动生成的car局部变量。collection

索引.html.haml

= render 'cars_list', collection: @cars, as: :this_car, date: @date
Run Code Online (Sandbox Code Playgroud)

_cars_list.html.haml

%h3 Look at these Cars!
%ul
  %li Something about this car
  %li this_car.description
%div
  = render 'calendars/calendar_stuff', this_car: this_car, date: date
Run Code Online (Sandbox Code Playgroud)

_calendar_stuff.html.haml

- if this_car.date == date
  %div 
    = this_car.date
Run Code Online (Sandbox Code Playgroud)