ruby-on-railsrenderpartial

Rails partial for array item not handling object data


the following view

<% @packageoffers.each do |packageoffer| %>
  <% if @packageoffers_mss.include?(packageoffer) %>
  <% elsif @availables.include?(packageoffer) %>
    <%= render 'packageoffer', collection: @packageoffers %>

is returning an NameError undefined local variable or method 'packageoffer' when trying to process the partial _packageoffer.html.erb upon a line like the second taht follows:

<% item_sale_price = @item_price.sale_price * params[:quantity].to_i %>
<% markup_price = ((item_sale_price + (packageoffer.price * @r * @q)) * (1 + (@user.markup.to_d / 100) ) )  %>

note: @item_price is itself an item of an array section and had to be declared as an instance variable to pass it along <% @item_price = @allotments.select{ |a| a.section_id == section.id }.first

Thus, notwithstanding following the rails documentation guidelines, I cannot process the array's item. Where lies the mistake?


Solution

  • You're using collection rendering incorrectly.

    Your line...

    <%= render 'packageoffer', collection: @packageoffers %>
    

    Renders a single partial, and passes a local variable called collection with a value of @packageoffers.

    The line you've written is a shorthand for:

    <%= render partial: 'packageoffer', locals: { collection: @packageoffers } %>
    

    If you want to render the entire collection and provide a partial name, you cannot use the render shorthand, you must use the explicit version of render partial:...:

    <%= render partial: 'packageoffer', collection: @packageoffers %>
    

    That said, it seems like your intent is to iterate over the collection, and conditionally render some items from it. In this case, you should not be using collection rendering at all, you should just use <%= render packageoffer %> to allow Rails to render the singular _packageoffer partial for each record.