Partials and Collections

Hi everyone,

I have a partial containing a few input elements to edit the properties of a vehicle. Those input fields are of course within a form, but they are not the only ones in there. Now when my page loads, I want to display all vehicles already added by the current user. So I thought I’d prepare a collection of appropriate vehicles in @vehicles and let the view render the vehicles using

<% if @vehicles %>
    <%= render :partial => "vehicle", :collection => @vehicles %>
<% end %>

The thing is, as I need to display more than one vehicle “form”, I need to give each input field a reference to the id of the underlying activercord. I’m trying this using

<%= text_field ‘vehicle[]’, ‘acquisition_cost’, { :class => “autosave_object”, :“tmt:required” => “true”, :“tmt:filters” => “numbersonly”, :size => 5, :tabindex => 4 } %>

As said in AWDWR the [] after the instance variable name adds the id to the name attribute of the textfield. Unfortunately, there is no instance variable called @vehicle in my controller since I only have the collection @vehicles. I get the following error

You have a nil object when you didn’t expect it!
You might have expected an instance of ActiveRecord::Base.
The error occured while evaluating nil.id_before_type_cast

Of course there is a local variable called vehicle. I can use it to manually build the necessary name attribute for the html input field. However, the input field is NOT connected to any instance variable, since there simply is none to connect to :frowning:

Any ideas how to approach this?

Martin Gamsjäger

Is this dirty ^^ =?

i = 1
@vehicles.each do |vehicle|
    instance_eval("@vehicle_#{i} = vehicle")

anyway it works :slight_smile:

Ohh yeah… That’s dirty :wink:

there is a method called each_with_index

@vehicles.each_with_index do |vehicle, index|

instance_eval( “@vechile_#{index} = vehicle” )


But in this situation you could, setup an instance variable in your partial.

<% @vehicle = vehicle %>

I don’t know that it’s any less dirty though.

Good Luck

Hi Daniel,

Thx for your tip! I will go with your solution <% @vehicle = vehicle %>. This seems the way to go for me, as I can avoid one of evals family members ^^