Topic: Populating select fields with observe_field()
EDIT: Apparently your forum software doesn't escape HTML characters in the subject field...I had "Populating <select> fields with observe_field()" and it showed a select box on the forum index "most recent post" column. By the way, I like your nice in the upper right-hand corner about forum software ![]()
Hello!
I am having an issue with populating a <select> field based on the data from another <select> field. I couldn't really find much documentation on this. In fact, the only relevant examples I had to go by where these two which, ironically, were both posting questions about this very topic. Neither had received any responses.
Basically, I have a few tables, each of which are also models: "school" (belongs_to :city), "state" (has_many :cities), "city" (belongs_to :state, has_many :schools). I want the user to be able to click on a state from the drop-down and have another <select> field generated below with the cities in that state.
Here is the code I have in my view file:
<h2>Find your school</h2>
<% form_for :school do |f| %>
<div id="find_school_state">
<p>First, select the state you live in:</p>
<%= f.select :state, State.find_all.collect { |s| [ s.name, s.id ] } %>
<%=
observe_field :school_state,
:url => { :controller => 'user', :action => 'update_cities_for_state' },
:update => 'find_school_city',
:with => "'state_id=' +value"
-%>
</div>
<div id="find_school_city" style="display: none">
<p>Second, select the city where you school resides:</p>
<%= f.select :city, '' %>
</div>
<% end -%>
On this note, I was wondering: I searched online, but no one really seems to explain how the "with" attribute of observe_field() works, but they all seem to use it in the same format (including the Rails wiki). Why does it work like that? Why not just ":with => { :state_id => value }" or something?
Anyway, back to the issue. So basically I figured that I needed a "update_cities_for_state" action and RJS file. In the user controller I added this method:
def update_cities_for_state
unless request.xhr?
redirect_to :controller => 'page'
else
@state = State.find(params[:state_id]) # state_id from <select> field
end
end
So now we have a "state" instance variable. Because the state model has_many :cities, I should be able to simply loop through the @state.cities attribute and pass that into my second <select> field, right? In the update_cities_for_state.rjs file I put:
page.select('find_school_city').show@cities = options_from_collection_for_select(@state.cities, 'id', 'name')
page.replace_html 'school_city', @cities
I am not even sure if I can use replace_html in that case, but that is what this person did.
I would really appreciate some assistance. Thank you!
Last edited by technel (2006-06-17 00:49:27)