##セレクトボックスでajaxを用いて、選択肢を絞りたい。
ですが、サイトの指示通りにやってもうまくうごきません。
【Rails】セレクトボックスの内容をAjaxを使用して動的に変更する
GoogleCromeのConsoleにエラーはありませんし、jQueryの他のイベントはちゃんと機能します。
Gemfile
gem 'rails', '~> 5.1.1' gem 'sqlite3' gem 'puma', '~> 3.7' gem 'sass-rails', '~> 5.0' gem 'uglifier', '>= 1.3.0' gem 'coffee-rails', '~> 4.2' gem 'turbolinks', '~> 5' gem 'jbuilder', '~> 2.5' # gem 'redis', '~> 3.0' # gem 'bcrypt', '~> 3.1.7' # gem 'capistrano-rails', group: :development gem 'bootstrap-sass' gem 'annotate' gem 'hirb' # モデルの出力結果を表形式で表示するGem gem 'hirb-unicode' # 日本語などマルチバイト文字の出力時の出力結果のずれに対応 gem 'jquery-rails' gem 'jquery-ui-rails'
route.rb
get 'hello/index' get 'hello/books'
book.rb
class Book < ApplicationRecord belongs_to :publisher end
publisher.rb
class Publisher < ApplicationRecord end
hello/index.html.erb
<h1 >Hello#index</h1> <%= select_tag :publisher_id, options_from_collection_for_select(Publisher.all, :id, :name) %> <%= select_tag :book_id, options_from_collection_for_select(Book.all, :id, :name) %> <script> $(function() { $('#publisher_id').change(function() { $.get({ url: "#{hello_books_path}", data: { publisher_id: $('#publisher_id').has('option:selected').val() } }); }); }); </script>
hello/books.js.erb
$('#book_id').html('<%= j(option_for_select(@books.pluck(:name,:id))) %>')
hello_controller.rb
class HelloController < ApplicationController def index;end def books @books = Book.where(publisher_id: params[:publisher_id]) end end
選択肢を変えたときの
ターミナルの反応
getは動いている模様
Started GET "/hello/index?publisher_id=1" for 127.0.0.1 at 2017-06-01 18:44:38 +0900 Processing by HelloController#index as */* Parameters: {"publisher_id"=>"1"} Rendering hello/index.html.erb within layouts/application Publisher Load (0.1ms) SELECT "publishers".* FROM "publishers" Book Load (0.1ms) SELECT "books".* FROM "books" Rendered hello/index.html.erb within layouts/application (2.1ms) Completed 200 OK in 76ms (Views: 61.3ms | ActiveRecord: 0.3ms)
book.js.erbが実行されていない?
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/06/02 00:37 編集