Passing a local variable to a nested partial

I have a page that displays a collection something like this:

index.html.haml

= render partial: 'cars_list', as: :this_car, collection: @cars 

_cars_list.html.haml

Edit: _cars_list has other information about an individual car.

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

_calendar_stuff.html.haml

 - if car.date == @date %div = car.date 

_cars_contoller.rb

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

What happens in the partial part of the calendar is that this_car always the first car in the car collection, i.e. the same date is printed over and over.

If I move the logic to _calendar_stuff in the cars_list part, then the printed result changes as expected.

So, it seems that Rails does not pass the local this_car object to the nested particle every time it displays a partial.

Does anyone know why?

PS If I structure the code with

 @cars.each do |car| render 'cars_list', locals: {this_car: car} end 

I get the same behavior.

+4
source share
1 answer

Try this refactoring and see if you get the desired result:

index.html.haml

 = render 'cars_list', collection: @cars, date: @date 

Get @date partial keyword and pass the @date instance @date as a local variable to encapsulate the logic in your scores. I got this moment from 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 

As you walked into @cars as collection , this partial will have a reference to a single local variable called car , which can then be passed to the next partial, and now locally date . Since partial visualization is located elsewhere here (more than calendars/ ), the partial keyword is explicitly required here.

_calendar_stuff.html.haml

 - if car.date == date %div = car.date 

Edit

We recommend moving the collection call to _cars_list.html.haml , but this is not suitable for the problem.

Edit 2

This is the version of the above code, if you still want to specify the local variable as this_car , so you would override the local variable car , which collection automatically generated.

index.html.haml

 = render 'cars_list', collection: @cars, as: :this_car, date: @date 

_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 

_calendar_stuff.html.haml

 - if this_car.date == date %div = this_car.date 
-1
source

All Articles