やりたい事・困っている事
親カテゴリを選択すると、子カテゴリのフォームの中身が動的に変わり、子カテゴリが選択されると、孫カテゴリも動的に変わるセレクトボックスをつくりたいです。
以下を参考にしました。
Ajaxでセレクトボックスの中身が動的に変わるRailsアプリの作り方(Qiita)
【Rails】Ajaxでセレクトボックスの中身が動的に変わる実装(3段構成)
具体的にはユーザーが記事(post)を投稿する際に
Prefecture(都道府県)→City(市区町村)→Area(エリア)
のカテゴリを動的に選択できるようにしたいです。
親・子の要素が動的に動いている状態だったのですが、孫要素を動かす為に修正したところ、
現在はエラーが出てしまいどのように修正すればいいのか分からなくなってしまいました。
ActionController::UrlGenerationError in CitiesController#index
No route matches {:action=>"index", :controller=>"areas", :prefecture_id=>#<City id: 33, name: "青森", prefecture_id: 17, created_at: "2019-11-02 09:42:41", updated_at: "2019-11-02 09:42:41">}, missing required keys: [:city_id]
【path: prefecture_city_areas_path(city)】
お分かりになる方がいらっしゃればご教授願います。
宜しくお願い致します。
(追記)試してみたこと・新たな問題
上記のエラーを解決する為に city.idを追記
Controller
class CitiesController < ApplicationController
def index
prefecture = Prefecture.find(params[:prefecture_id])
cities = prefecture.cities.map do |city|
{
id: city.id,
name: city.name,
~~path: prefecture_city_areas_path(city)~~
path: prefecture_city_areas_path(city.id, city)
}
end
render json: cities
end
end
エラーは解消され、親要素から子要素は順調に動いているのですが、
孫要素に反応がありません。
console.log($(this).find('option:selected').data().grandchildrenPath);
undefined となってしまいます。
どなたかお分かりになる方いらっしゃいましたらお力添えをお願いいたします。
コード
view
<div>
<% prefecture_options = Prefecture.order(:id).map { |c| [c.name, c.id, data: { children_path: prefecture_cities_path(c) }] } %>
<%= f.select :prefecture_id, prefecture_options, { include_blank: true }, class: 'select-parent' %>
</div>
<div>
<% cities = @post.prefecture.try(:cities) || [] %>
<% city_options = cities.map { |c| [c.name, c.id, data: { path: prefecture_city_areas_path(c) }] } %>
<%= f.select :city_id, city_options, { include_blank: true }, class: 'select-children' %>
</div>
<div>
<% areas = @post.city.try(:areas) || [] %>
<% area_options = areas.map { |c| [c.name, c.id] } %>
<%= f.select :area_id, area_options, { include_blank: true }, class: 'select-grandchildren' %>
</div>
$(document).on 'turbolinks:load', ->
replaceSelectOptions = ($select, results) ->
$select.html $('<option>')
$.each results, ->
option = $('<option>').val(this.id).text(this.name)
if this.path
option.data('path', this.path)
$select.append(option)
#親から子
replaceChildrenOptions = ->
childrenPath = $(@).find('option:selected').data().childrenPath
$selectChildren = $(@).closest('form').find('.select-children')
if childrenPath?
$.ajax
url: childrenPath
dataType: "json"
success: (results) ->
replaceSelectOptions($selectChildren, results)
error: (XMLHttpRequest, textStatus, errorThrown) ->
console.error("Error occurred in replaceChildrenOptions")
console.log("XMLHttpRequest: #{XMLHttpRequest.status}")
console.log("textStatus: #{textStatus}")
console.log("errorThrown: #{errorThrown}")
else
replaceSelectOptions($selectChildren, [])
#子から孫
replaceGrandChildrenOptions = ->
grandchildrenPath = $(@).find('option:selected').data().Path
$selectGrandChildren = $(@).closest('form').find('.select-grandchildren')
console.log($(@).find('option:selected').data().grandchildrenPath)
if grandchildrenPath?
$.ajax
url: grandchildrenPath
dataType: "json"
success: (results) ->
replaceSelectOptions($selectGrandChildren, results)
error: (XMLHttpRequest, textStatus, errorThrown) ->
console.error("Error occurred in replaceChildrenOptions")
console.log("XMLHttpRequest: #{XMLHttpRequest.status}")
console.log("textStatus: #{textStatus}")
console.log("errorThrown: #{errorThrown}")
else
replaceSelectOptions($selectGrandChildren, [])
$('.select-parent').on
'change': replaceChildrenOptions
$('.select-children').on
'change': replaceGrandChildrenOptionsコードの表示(ブロック)
Controller
class CitiesController < ApplicationController
def index
prefecture = Prefecture.find(params[:prefecture_id])
cities = prefecture.cities.map do |city|
{
id: city.id,
name: city.name,
path: prefecture_city_areas_path(city)
}
end
render json: cities
end
end
class AreasController < ApplicationController
def index
city = City.find(params[:city_id])
render json: city.areas.select(:id, :name)
end
end
Model
class Post < ApplicationRecord
belongs_to :prefecture, optional: true
belongs_to :city, optional: true
belongs_to :area, optional: true
end
class Prefecture < ApplicationRecord
has_many :cities, ->{ order(:id) }, dependent: :destroy
end
class City < ApplicationRecord
belongs_to :prefecture, optional: true
has_many :areas, ->{ order(:id) }, dependent: :destroy
end
class Area < ApplicationRecord
belongs_to :city, optional: true
end
Routing
Rails.application.routes.draw do
resources :posts, only: [:index, :show, :new, :create, :edit, :update, :destroy] do
collection do
get '/:id/city' => 'posts#city', as: "city"
end
end
resources :prefectures, only: [] do
resources :cities, only: :index do
resources :areas, only: :index
end
end
end
-
気になる質問をクリップする
クリップした質問は、後からいつでもマイページで確認できます。
またクリップした質問に回答があった際、通知やメールを受け取ることができます。
クリップを取り消します
-
良い質問の評価を上げる
以下のような質問は評価を上げましょう
- 質問内容が明確
- 自分も答えを知りたい
- 質問者以外のユーザにも役立つ
評価が高い質問は、TOPページの「注目」タブのフィードに表示されやすくなります。
質問の評価を上げたことを取り消します
-
評価を下げられる数の上限に達しました
評価を下げることができません
- 1日5回まで評価を下げられます
- 1日に1ユーザに対して2回まで評価を下げられます
質問の評価を下げる
teratailでは下記のような質問を「具体的に困っていることがない質問」、「サイトポリシーに違反する質問」と定義し、推奨していません。
- プログラミングに関係のない質問
- やってほしいことだけを記載した丸投げの質問
- 問題・課題が含まれていない質問
- 意図的に内容が抹消された質問
- 過去に投稿した質問と同じ内容の質問
- 広告と受け取られるような投稿
評価が下がると、TOPページの「アクティブ」「注目」タブのフィードに表示されにくくなります。
質問の評価を下げたことを取り消します
この機能は開放されていません
評価を下げる条件を満たしてません
質問の評価を下げる機能の利用条件
この機能を利用するためには、以下の事項を行う必要があります。
- 質問回答など一定の行動
-
メールアドレスの認証
メールアドレスの認証
-
質問評価に関するヘルプページの閲覧
質問評価に関するヘルプページの閲覧
まだ回答がついていません
15分調べてもわからないことは、teratailで質問しよう!
- ただいまの回答率 88.22%
- 質問をまとめることで、思考を整理して素早く解決
- テンプレート機能で、簡単に質問をまとめられる
質問への追記・修正の依頼
perpouh
2019/11/19 14:45
>console.log($(@).find('option:selected').data().grandchildrenPath)
view側にdata-grandchildrenPath出てきてなくないですか?