やりたいこと
現在、都道府県と市区町村を連動させるプルダウンを実装したく、こちらのページを参考に機能を実装しています。
https://teratail.com/questions/14444
現在の状況と致しましては、都道府県は表示されていて、都道府県id=1
に当たる、北海道の市区町村のみが表示されている状態です。
しかし、他の県を選んでも、プルダウンが連動しません。これを解決したいです。
わかりやすくするために、上記のページに書いてあるコードを引用させてください。
#view <%= form_for @post do |post| %> 都道府県 <%= post.collection_select :mst_prefecture , MstPrefecture.all,:id,:name %><br /> 市区町村 <%= render partial: 'shared/cities', locals: { prefecture_id: MstPrefecture.first.id } %> #shared/cities <%= collection_select :post , :mst_city, MstCity.where(prefecture_id: prefecture_id),:id,:name %> #posts_controller.rb def cities_select if request.xhr? render partial: 'shared/cities', locals: { prefecture_id: params[:prefecture_id]} end end #config/routes.rb resources :posts do collection do get :cities_select end end #posts.coffee $(document).on 'change', '#post_mst_prefecture', -> $.ajax( type: 'GET' url: '/posts/cities_select' data: { prefecture_id: $(this).val() } ).done (data) -> $('#post_mst_city').html(data) #post.rb class Post < ActiveRecord::Base belongs_to :mst_prefecture belongs_to :mst_city end # mst_prefecture.rb class MstPrefecture < ActiveRecord::Base has_many :mst_cities end # ms_city.rb class MstCity < ActiveRecord::Base belongs_to :mst_prefecture end
そして私のコードがこちらです。
#_micropost_form.html.erb <%= form_for(@micropost) do |f| %> <%= render 'shared/error_messages', object: f.object %> <div class="field"> <%= f.text_area :content, placeholder: "Compose new micropost..." %> </div> <div class="field"> <%= f.label :prefecture_id,"都道府県" %> <%= f.collection_select :prefecture_id, Prefecture.all, :id, :name, include_blank: "選択してください" %> </div> <div class="field"> <%= f.label :city_id,"市区町村" %> <%= render partial: 'shared/cities', locals: {prefecture_id: Prefecture.first.id} %> </div> <%= f.submit "Post", class: "btn btn-primary" %> <% end %> #shared/cities <%= collection_select :post, :city_id, City.where(prefecture_id: prefecture_id), :id, :name, prompt: "" %> #microposts_controller.rb class MicropostsController < ApplicationController before_action :authenticate_user!, only: [:create, :destroy] def create @micropost = current_user.microposts.build(micropost_params) if @micropost.save flash[:success] = "Micropost created!" redirect_to root_url else render 'static_pages/home' end end def cities_select if request.xhr? render partial: 'shared/cities', locals: {prefecture_id: params[:prefecture_id]} end end #config/routes.rb resources :microposts, only: [:create, :destroy] resources :microposts do collection do get :cities_select end end #microposts.coffee $(document).on 'change', '#post_prefecture_id', -> $.ajax( type: 'GET' url: '/microposts/cities_select' data: { prefecture_id: $(this).val() } ).done (data) -> $('#post_city_id').html(data) #micropost.rb class Micropost < ApplicationRecord belongs_to :user belongs_to :prefecture, optional: true belongs_to :city default_scope -> { order(created_at: :desc) } validates :user_id, presence: true validates :content, presence: true, length: { maximum: 1000 } end # prefecture.rb class Prefecture < ApplicationRecord has_many :microposts has_many :cities end # city.rb class City < ApplicationRecord belongs_to :prefecture end
予想できるおかしい部分と試したこと
パーシャルでcollection_selectに渡している、第一引数(:post)がおかしいのではないかと思っています。
#shared/cities <%= collection_select :post, :city_id, City.where(prefecture_id: prefecture_id), :id, :name, prompt: "" %>
collection_selectの場合は、第一引数にオブジェクト名を入れるとのことでしたので、最初は(:micropost)
を入れたところ、第二引数の(city_id)にNomethodエラーが出ました。
次に、(:microposts)
の複数形の引数を渡したところ、エラーが出なくなりました。
現在は(:post)にしていますが、何故かこれでもエラーが出ません。
次に、参考ページのように、form_for @micropost do |post|
としてみて、fは使わずに、試してみましたが、これも結果は変わりませんでした。
私のコードの場合の、「オブジェクト名」とは何に当たるのでしょうか??
次に、こちらのコードがおかしいと思いました。
#micropost.coffee $(document).on 'change', '#post_prefecture_id', -> $.ajax( type: 'GET' url: '/microposts/cities_select' data: { prefecture_id: $(this).val() } ).done (data) -> $('#post_city_id').html(data)
一行目の最終行の、 ~'change', '#post_prefecture_id', ->
こちらの部分ですが、トリガーにformヘルパーから自動生成されるIDが使用されているのがわかりました。
こちらは参考ページと同様にしていますが、$(document).on 'change', '#prefecture_id', ->
等でも試してみましたが、ダメでした。
こちらの自動生成されるIDは、どのようにすれば確認できるのでしょうか??
アプリケーションログを見てみると、何かわかるかもしれないと思い、確認して見ました。
User Load (0.6ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 ORDER BY `users`.`id` ASC LIMIT 1 web_1 | ↳ app/controllers/static_pages_controller.rb:3 web_1 | Rendering static_pages/home.html.erb within layouts/application web_1 | (0.6ms) SELECT COUNT(*) FROM `microposts` WHERE `microposts`.`user_id` = 1 web_1 | ↳ app/views/shared/_user_info.html.erb:3 web_1 | Rendered shared/_user_info.html.erb (3.6ms) web_1 | Rendered shared/_error_messages.html.erb (0.5ms) web_1 | Prefecture Load (0.9ms) SELECT `prefectures`.* FROM `prefectures` web_1 | ↳ app/views/shared/_micropost_form.html.erb:8 web_1 | Prefecture Load (0.5ms) SELECT `prefectures`.* FROM `prefectures` ORDER BY `prefectures`.`id` ASC LIMIT 1 web_1 | ↳ app/views/shared/_micropost_form.html.erb:12 web_1 | City Load (1.2ms) SELECT `cities`.* FROM `cities` WHERE `cities`.`prefecture_id` = 1 web_1 | ↳ app/views/shared/_cities.html.erb:1 web_1 | Rendered shared/_cities.html.erb (10.2ms) web_1 | Rendered shared/_micropost_form.html.erb (47.4ms) web_1 | Rendered static_pages/home.html.erb within layouts/application (78.3ms) web_1 | Rendered layouts/_shim.html.erb (0.3ms) web_1 | Rendered layouts/_header.html.erb (0.9ms) web_1 | Rendered layouts/_footer.html.erb (0.5ms) web_1 | Completed 200 OK in 437ms (Views: 415.5ms | ActiveRecord: 3.9ms)
都道府県の読み込みはできていて、市区町村のプルダウンにも、````cities.
prefecture_id` = 1```こちらに該当する、北海道の市区町村が表示されています。
しかし、他の県を選択しても、市区町村が切り替わりません。
どんな些細なことでも、おかしいと思う部分をご指摘いただけると、誠に嬉しいです。
よろしくお願いします。
あなたの回答
tips
プレビュー