RJS: Ajaxified select_tag

Since I did not receive the expected answer to my last question , I will try to simplify and narrow my question:

How can I create a drop-down menu that uses AJAX (without a submit button) to invoke the show action of a specific controller?

The following things are given:

An association model is a HABTM Projects category, so the drop-down menu consists of all category names.

partial view where the dropdown menu should be implemented. Below the drop-down menu is a list of projects that should be changed in accordance with the choice made in the drop-down 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>

Category Controller with the caller:

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

, - :

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

? !

+3
1

:

<% 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 %>

html, ( format.html).

[: id]

@category = Category.find(params[:id])
+7

Source: https://habr.com/ru/post/1703702/


All Articles