views:

1102

answers:

1

Since I didn't get the expected answer on my last question I'll try to simplify and narrow my question:

How can I build a dropdown-menu that uses AJAX (no submit-button) to call the show action of a certain controller?

The following things are given:

Model-Association is Categories HABTM Projects, therefore the dropdown-menu consists of all category names.

The view partial where the dropdown-menu should be implemented. Below the dropdown menu is a list of projects that should change according to the choice made in the dropdown menu:

   <!-- placeholder for AJAX dropdown menu -->

   <!-- list of projects related to categories chosen by the select tag -->
   <ul class="projects">
     <% @projects.each do |_project| %>
       <li>
         <%= link_to(_project.name, _project) %>
       </li>
     <% end %>
   </ul>

The Categories controller with the show-action that should be called:

class CategoriesController < ApplicationController
  def show
    # params[:id] should be the choice the user made in the dropdown menu
    @category = Category.find(params[:id])
    @projects = @category.projects.find(:all)

    respond_to do |format|
      format.html # show.html.erb
      format.js   # needed for ajax response?
    end
  end

  def index
    @projects = Category.find(params[:id]).projects.find(:all)
    @category = @project.categories.first

    respond_to do |format|
      format.html # index.html.erb
    end
  end 
end

The route to call the show-action in the Categories controller:

category GET    /categories/:id    {:controller=>"categories", :action=>"show"}

How would you implement this? Any help is very apreciated!

+3  A: 

How about this:

<% form_for :category, :url => { :action => "show" } do |f| %>
  <%= select_tag :id, options_from_collection_for_select(Category.find(:all), :id, :name),
  { :onchange => "this.form.submit();"} %>
<% end %>

That will call a traditional html call, so it will refresh the entire page (and respond to format.html).

Then the controller will find the category by the submitted [:id]

@category = Category.find(params[:id])
chap
Nice one! Thanks, I never thought of the idea of making a traditional html-call by using javascript. What value will have :category and what will have :id? Wouldn't that have the same value?
Javier
It's unnecessary, but then you have to use the select_tag, I've updated my answer to show how.
chap