Maybe I’m just trying too hard, because I have done this plenty of
times with plain old javascript before Rails entered my life. But now
that I’m trying to work within the Rails system of form_for and such,
I am finding that what should be a simple task has become arduous
beyond compare. I’m ready to tear out what little hair I have left,
and I have yet to find anything online that addresses what I thought
would be a common scenario.
So, the scenario:
A user create/edit page. When a user selects US or Canada, the drop
down loads accordingly. If he selects a different country, the
dropdown disappears. When the form is submitted, the user and his
address are saved accordingly.
User: has_one :address
Address: has_one :state, has_one :country
edit.rhtml:
<% form_for :user, :url => {:action => “update”, :id => @user} do |f|
%>
<%= render :partial => “user_form”, :locals => {:f => f} %>
<% end %>
_user_form.rhtml:
First name: <%= f.text_field :first_name %>
Last name: <%= f.text_field :first_name %>
<% fields_for :address do |a| %>
City: <%= a.text_field :city %>
Country: <%= a.select :country_id, COUNTRIES %>
State: <%= a.select :state_id, STATES %>
<% end %>
At first, I tried putting the state selector and text in its own
partial, thinking that via a custom onchange event on the country
selector and by using RJS I would be able to reload the state selector
from a controller method or hide it altogether. But in practice it
can’t be done because the state selector needs a form reference and
the controller can’t pass that in. It got ugly real fast.
So where I stand now, I’m looking at writing a custom javascript
method, fired from an onchange event on the country selector, that
would reload the contents of the state selector. Have I missed some
magical rails ingredient or helper that would make this better? Has it
just been too long a day? Any help appreciated.