views:

465

answers:

4

the following is my dropdown to select chat rooms:

<% form_for :chat_room do |form| %>
          <%= form.select(:title, @chat_rooms.collect! {|x| x.title},{:include_blank =>'select a chat room'}) %>
        <% end %>

My routes are:

ActionController::Routing::Routes.draw do |map|

  map.resource :account, :controller => "users"
  map.resources :poll
  map.resources :users,:has_many => :stories
  map.resources :chat_rooms ,:member => {:create_message => :post},:collection => {:ajax_updater=>:get}
  map.logout 'logout', :controller => 'user_sessions', :action =>'destroy'
  map.resource :user_session
  map.resource  :welcome
  map.connect '/', :controller => 'welcome', :action => 'index'

  map.connect ':controller/:action/:id'
  map.connect ':controller/:action/:id.:format'
end

On changing values in the drop down I want to navigate to a particular chatroom chosen. How do I do that?

+4  A: 

one (simple) way would be to add the :onchange parameter to the select helper

form.select(:title, @chat_rooms.collect! {|x| [x.title, x.id] },{:include_blank =>'select a chat room'}, :onchange => 'window.location.href = "chat_rooms/" + this.getAttribute("value")')
andi
Just a reminder: Enumerable#collect! is a destructive method. You want Enumerable#collect instead. And generally, Enumerable#map (which does the same thing) is preferable for historical reasons.
Bob Aman
A: 

Just a quick note, I know you didn't ask about it. But when you are working with chats be sparse with ajax polling to check for new chats. If you weren't doing so already check out Juggernaut.

Maran
+1  A: 

This is just a variation of the approach that andi has used above but...

The pattern I typically use now is to write a simple javascript function that will load the selected path:

CHATROOM.display_selected = function(id, base_path)
{
  window.location = base_path + '?id=' + id;  
}

This function is then called by the onchange of the select tag:

select_tag("chat_room",options_for_select(chat_rooms, selected), :onchange => "CHATROOM.display_selected(this.value, '#{chat_rooms_path}')")

Where the path variable is the base path for chat_rooms.

paulthenerd
+1  A: 

Assuming you're using jQuery (and who isn't these days), something like this would work:

ERB View (corrected from above):

<% form_for :chat_room do |form| %>
  <%= form.select(:title, @chat_rooms.map { |c| [c.title, c.id] }, {:include_blank =>'select a chat room'}) %>
<% end %>

JS:

$(document).ready(function () {
  $("#chat_room_title").change(function(event) {
    window.location = "/chat_rooms/" + $("#chat_room_title").val() + "/";
  });
});

The Prototype code would be very similar.

Bob Aman