Hello -
I am fairly new to Ruby on Rails, but feel like I am learning quick.
I have what seems to be a fairly unique issue as I cannot find much
out there that describes what I’m seeing. Hopefully it’s a very
simple fix, and I simply can’t see the forest through all the trees!
I am attempting to create 2 related drop-down lists in the same
form_for, both using collection_select.
On the first drop-down, I have an onChange “remote_function” call that
I want to send an AJAX call to the controller and filter the list in
the 2nd drop-down based on what was selected in the first. In the
controller method, I then call page.replace_html to render a partial.
In the partial is the “updated/filtered” 2nd collection_select drop-
down list.
The remote_function works fine and calls the Controller method when
the first drop-down changes. I am also able to pass the selected value
to the method and filter the records returned. The problem occurs
when the controller attempts to render the partial, I get the
following error:
ActionView::TemplateError (undefined local variable or method `f’ for
#ActionView::Base:0xb6e7b2f4) on line #1 of app/views/listings/
_automodels.html.erb:
<%= f.collection_select :model, @automodels, :model, :model, {:prompt
=> “-Select a Make First-”} %>
This leads me to believe that the “f” variable the rest of the fields
in the form_for are using is not available to the newly-replaced
“collection_select”, but I’m not sure why?
If the partial contains a simple HTML instead of the
collection_select, the replace_html works fine.
Source code is worth 1,000 words, so here it is:
listings/new.html.erb
- <% form_for([@user, @listing]) do |f| %>
- <%= f.error_messages %>
-
-
<%= f.label :make %><br />
-
<%= f.collection_select :make, @automakes, :make, :make,
{:prompt => “-Select a Make-”}, {:onChange => remote_function(:url =>
{:action => ‘get_automodels’}, :with => “‘make=’ + this.value”)} %>
6.
7.
8. <%= f.label “Model:” %>
9.
10. <%= f.collection_select :model,
@automodels, :model, :model, {:prompt => “-Select a Make First-”} %>
11.
12.
13.
14. <%= f.submit ‘Create’ %>
15.
16. <% end %>
listings_controller.rb
- def get_automodels
- @automodels = Automodels.find_by_make(params[:make])
- render :update do |page|
-
page.replace_html('automodelsdiv', :partial => 'automodels')
- end
- end
_automodels.html.erb
- <%= f.collection_select :model, @automodels, :model, :model,
{:prompt => “-Select a Make First-”} %>