简体   繁体   中英

Can 'locals' be used with 'collection' when rendering partials in Rails?

Everything works okay when I try to render a partial like this:

= render :partial => "/shared/enquiry/car_type", :collection => @enquiry.available_car_types

However, if I also want to pass a variable (in this case 'path', because I'm sharing this partial across two forms), the path is not available to me:

= render :partial => "/shared/enquiry/car_type", :collection => @enquiry.available_car_types, :locals => {:path => customers_enquiry_path}

I've tried moving things around, but nothing appears to work, leading me to believe one cannot use locals with collections. Any help would be appreciated.

Gav

Like the guides said, specify the :as option in the call to the partial

在此处输入图片说明

For Rails 4.x, if you pass the collection directly to render (which you must do if you want to use automatic partial selection for a heterogeneous collection), the next parameter is interpreted as a hash of locals.

Try the following:

= render @enquiry.available_car_types, :path => customers_enquiry_path

What version are you using? Using my 2.3.5 I'm able to do just that:

render :partial => "/site_articles/article", :collection => @site_articles, :locals => { :footer => true }

, which you can find explained in other places, such as 3.4.6 of this .

@Gav, you are running into two issues.

  1. render ignores the locals option when passing the collection as the first parameter. You need to instead specify the partial and collection parameter options, as you have in your second example.

  2. path likely falls into the realm of a reserved word. Try using something else.

No you can't use them together. Ref this

I think you have to do something like following

  <% for ad in @enquiry.available_car_types %>
    <%= render :partial => "/shared/enquiry/car_type", :locals =>{ :ad => ad, :path =>customers_enquiry_path } %>
  <% end %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM