Hi All,
I'm probably making this way too complicated. I know
that everything I have in mind here is possible, but I can't seem to
figure this out. Clearly, I've put Rails down for far too long. I've looked around for a solution on railsforum and rails-talk, but to no avail. I think that only made matters worse.
Ignoring the bigger picture for a moment, I'd like to present the user with two drop-down menus of constant options. The first menu is a list of States. The second menu is a list of USGS water monitoring stations. I'd like to have two ajax-esque actions. I'm currently stuck on the first (although, i haven't really worked on the second. I'm sure I'll get stuck there too). (For the second action, more of the same. Update the page with the parsed and presented real-time data from the station upon station selection.)
When the user selects a state from the state menu, I'd like the station menu to update with just the list of the stations in that state. Sounds relatively straight forward. What combination of js, controller actions, and voodoo will make this work? I've tried more than a few.
My understanding: I think I should have a form where the selection :onchange invokes an Ajax.Updater action. This action should pass the state_id to a controller action that will make a new @stations to then update the the station select collection. I think this is a GET action.
What I have:
Rails 2.0
Routes: standard
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
**I have not set map.resources**
Two models: 1) States {name, abbrev}; 2) Stations {sitename, siteno, state_id} (stations is ~4000 rows)
Associations: states have_many :stations; station belongs_to :state
#controller
class WaterController < ApplicationController
def index
@states = State.find(:all).sort_by{|s|
s.name }
@stations = Station.find(:all).sort_by{|t|
t.state.name}
#@stations = []
respond_to do |format|
format.html
end
end
def update_sites
@stations = Station.state.find(params[:id]).sort_by{|n| n.sitename}
end
end
#view
#index.html.erb
<% form_for :water do |f| %>
<%= f.collection_select(:state_id, @states, :id, :name, {:prompt => "Select a state"}, {:onchange => 'updateSites();'} )%>
<%= f.collection_select(:station_id, @stations, :siteno, :sitename, :prompt => "Select a station") %>
<% end %>
#application.js
updateSites = function(){
new Ajax.Updater ('water_station_id',
'update_sites/'+this[this.selectedIndex].value,
{asynchronous:true, evalScripts:true, parameters:'authenticity_token='+encodeURIComponent('"+form_authenticity_token.to_s+"')});
}
I appreciate any thoughts on where I have gone wrong.
I thought that this would be a quick and easy project to get working and actually deploy (which is something that I have not done, as localhost doesn't count).
If you think that you'd like to help (it's obvious that I could use some help), I'll send you an even lengthier email with my ideas of what I'd like to accomplish.
Again, thanks.
Chase