質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Ajax

Ajaxとは、Webブラウザ内で搭載されているJavaScriptのHTTP通信機能を使って非同期通信を利用し、インターフェイスの構築などを行う技術の総称です。XMLドキュメントを指定したURLから読み込み、画面描画やユーザの操作などと並行してサーバと非同期に通信するWebアプリケーションを実現することができます。

Q&A

解決済

1回答

2043閲覧

Rails4 AJAX通信selectbox

smith

総合スコア73

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Ajax

Ajaxとは、Webブラウザ内で搭載されているJavaScriptのHTTP通信機能を使って非同期通信を利用し、インターフェイスの構築などを行う技術の総称です。XMLドキュメントを指定したURLから読み込み、画面描画やユーザの操作などと並行してサーバと非同期に通信するWebアプリケーションを実現することができます。

0グッド

0クリップ

投稿2015/04/09 10:17

親カテゴリを選択すると子カテゴリが選択できないtextのような表示になってしまいます。
そのままsubmitを押してvalidateで戻ってくると
ただしくselectboxとして表示されます。
親カテゴリを選択したタイミングでただしくselectboxとして表示させるにはどうしたら良いでしょうか

![イメージ説明]WIDTH:589

lang

1#Item controller 2 3def new 4 @item = current_user.items.build 5 end 6 7 def create 8 @item = current_user.items.build(item_params) 9 respond_to do |format| 10 if @item.save 11 format.html { redirect_to @item, notice: 'アイテムを登録しました' } 12 13 format.json { render :show, status: :created, location: @item } 14 else 15 16 format.html { render :new } 17 format.json { render json: @item.errors, status: :unprocessable_entity } 18 end 19 end 20 end 21 22#Item view 23 24 <div class="form-group"> 25 <label for="category" class="col-sm-3 control-label">カテゴリ&ensp;<span class="text-danger glyphicon glyphicon-asterisk"></span></label> 26 <div class="col-sm-9 col-md-3 col-lg-3"> 27 <%= f.select :category_id, category_collection(Category.find_by_name('root')), {:include_blank => '選択してください'}, {class: 'form-control select select-default category-select'} %> 28 </div> 29 </div> 30 31 32 <div class="form-group"> 33 <label for="sub_category" class="col-sm-3 control-label">サブカテゴリ&ensp;<span class="text-danger glyphicon glyphicon-asterisk"></span></label> 34 <div class="col-sm-9 col-md-3 col-lg-3"> 35 <%= f.select :sub_category_id, category_collection(item.category), {:include_blank => '選択してください'}, {class: 'form-control select select-default sub-category-select'} %> 36 </div> 37 </div> 38 39 40# Item model 41class Item < ActiveRecord::Base 42 belongs_to :category 43 belongs_to :sub_category, class_name: 'Category', foreign_key: :sub_category_id 44end

lang

1class Category < ActiveRecord::Base 2 has_many :items 3 has_many :sub_categories, ->{ order(:code) }, class_name: 'Category', foreign_key: 'parent_id' 4 belongs_to :categories, class_name: 'Category', foreign_key: 'parent_id' 5end

lang

1#AJAX 2$ -> 3 do -> 4 appendOptions = ($select, results) -> 5 option = $('<option>') 6 $select.append(option) 7 $.each results, -> 8 option = $('<option>') 9 option.val(this.id) 10 option.text(this.name) 11 $select.append(option) 12 13 replaceSubCategoryOptions = -> 14 url = $(@).find('option:selected').data().subCategoriesPath 15 $select = $(@).closest('form').find('.sub-category-select') 16 if url? 17 $.ajax 18 url: url 19 dataType: "json" 20 success: (results) -> 21 $('.field-sub-category').toggle(results.length > 0) 22 $select.empty() 23 appendOptions($select, results) 24 else 25 $('.field-sub-category').hide() 26 $select.empty() 27 28 $('.category-select').change(replaceSubCategoryOptions)

lang

1#Category helper 2module CategoriesHelper 3 def category_collection(category) 4 (category.try(:sub_categories) || []).map do |c| 5 [c.name, c.id, { data: { sub_categories_path: category_sub_categories_path(c) } }] 6 end 7 end 8end

lang

1#ルーティング 2resources :categories, only: [] do 3 get :sub_categories 4end

サーバログ
Started GET "/categories/6/sub_categories" for 127.0.0.1 at 2015-04-09 19:08:13 +0900
Processing by CategoriesController#sub_categories as JSON
Parameters: {"category_id"=>"6"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."deleted_at" IS NULL AND "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
Category Load (0.2ms) SELECT "categories".* FROM "categories" WHERE "categories"."name" = 'root' LIMIT 1
Category Load (0.1ms) SELECT "categories".* FROM "categories" WHERE "categories"."id" = ? LIMIT 1 [["id", 6]]
Category Load (0.1ms) SELECT "categories".* FROM "categories" WHERE "categories"."parent_id" = ? ORDER BY "categories"."code" ASC [["parent_id", 6]]
Completed 200 OK in 25ms (Views: 3.1ms | ActiveRecord: 0.6ms)

seeds.rb
#親カテゴリ
Category.create(:name => 'root', :code => 000000, :parent_id => 0)
Category.create(:name => 'メンズ', :code => 100000, :parent_id => 1)#2
Category.create(:name => 'レディース', :code => 200000, :parent_id => 1)#3
Category.create(:name => 'キッズ', :code => 300000, :parent_id => 1)#4
Category.create(:name => 'インテリア', :code => 400000, :parent_id => 1)#5
Category.create(:name => '家電製品', :code => 500000, :parent_id => 1)#6
Category.create(:name => '本', :code => 600000, :parent_id => 1)#7
Category.create(:name => 'チケット', :code => 700000, :parent_id => 1)#8
Category.create(:name => 'おもちゃ', :code => 800000, :parent_id => 1)#9
Category.create(:name => 'エンターテインメント', :code => 900000, :parent_id => 1)#10
Category.create(:name => 'スポーツ', :code => 1000000, :parent_id => 1)#11

#メンズ子カテゴリ
Category.create(:name => 'トップス', :code => 100100, :parent_id => 2)
Category.create(:name => 'アウター', :code => 100200, :parent_id => 2)
Category.create(:name => 'パンツ', :code => 100300, :parent_id => 2)
Category.create(:name => '靴', :code => 100400, :parent_id => 2)
Category.create(:name => '帽子', :code => 100500, :parent_id => 2)
Category.create(:name => 'その他', :code => 100600, :parent_id => 2)

#レディース子カテゴリ
Category.create(:name => 'トップス', :code => 200100, :parent_id => 3)
Category.create(:name => 'アウター', :code => 200200, :parent_id => 3)
Category.create(:name => 'パンツ', :code => 200300, :parent_id => 3)
Category.create(:name => '靴', :code => 200400, :parent_id => 3)
Category.create(:name => '帽子', :code => 200500, :parent_id => 3)
Category.create(:name => 'その他', :code => 200600, :parent_id => 3)

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

kuboon

2015/04/10 06:42

> $select.empty() > appendOptions($select, results) この empty は期待通り機能していますか? この時点での results の内容をチェックしてもらえますか?
smith

2015/04/20 02:38

select2を使っていたのが原因でした。
guest

回答1

0

自己解決

セレクトボックスにSelect2を使用していたため

投稿2015/04/20 02:42

smith

総合スコア73

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問