item show でcategory modelのnameカラムで表示するにはどうしたら良いでしょうか
現状はitem modelのカラムにはcategory_idのint型が入っていています。
item controller
lang
1 2 def list_params 3 params.require(:category_id) 4 end 5 6 def list 7 selected_category = Category.where(parent_id: list_params)#list_paramsで拾ったcategory_idが親カテゴリになっている子カテゴリを集める 8 9 childs = selected_category.sort{|a, b| a.code <=> b.code} 10 data = [] 11 childs.each do |child| 12 data << {id: child.id, name: child.name} 13 end 14 respond_to do |format| 15 format.json { render json: data } 16 end 17 end 18 19 20 def category_select 21 root = Category.find(1) 22 @categories = root.childs.sort{|a, b| a.code <=> b.code} 23 @childs = @categories[0].childs.sort{|a, b| a.code <=> b.code} 24 end
item view
lang
1 2 <!-- アイテム情報 --> 3 <div class="panel panel-default"> 4 <div class="panel-heading"> 5 <h3 class="panel-title"> アイテム情報</h3> 6 </div> 7 <ul class="list-group list-group-flush text-left"> 8 9 <li class="list-group-item"> 10 <%= @item.content %> 11 </li> 12 13 14 15 16 <li class="list-group-item"> 17 <strong>カテゴリ:</strong> 18 <%= @item.category_id %> 19 </li> 20 <li class="list-group-item"> 21 <strong>subカテゴリ:</strong> 22 <%= @item.sub_category_id %> 23 </li> 24 25 <li class="list-group-item"> 26 <strong>コンディション:</strong> 27 <%= @item.condition %> 28 </li> 29 30 <li class="list-group-item"> 31 <strong>発送元:</strong> 32 <%= @item.area %> 33 </li> 34 35 <li class="list-group-item"> 36 <strong>執行日:</strong> 37 <%= @item.limit_day %> 38 </li> 39 </ul> 40 </div> 41
lang
1$(document).on('change', '#category_select', function(evt) { 2 $.ajax({ 3 type: 'GET', 4 url: 'categoreis/list', 5 dataType: 'json', 6 data: { 7 category_id: $("#category_select option:selected").val() 8 }, 9 error: function(jqXHR, textStatus, errorThrown) { 10 console.log("AJAX Error: " + textStatus); 11 }, 12 success: function(data, textStatus, jqXHR) { 13 $("#child_select").empty(); 14 if (data.length == 0) { 15 $("#child_select").hide(); 16 } else { 17 $("#child_select").show(); 18 } 19 $.each(data, function(idx, child) { 20 // console.log("" + item.code + ":" + item.name); 21 $("#child_select").append('<option value="' + child.id + '">' + child.name + '</option>'); 22 }); 23 console.log("Dynamic country select OK!"); 24 } 25 }); 26 }); 27 28
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2014/12/29 02:36