発生している問題
地方プルダウンの結果によって、都道府県プルダウンの内容を変える機能を作っています
地方の結果をAjaxで送り、該当の都道府県を取得して、.js.erbにrenderするところまでは出来たと思うのですが表示が変わりません
結果もcompleted 200で成功してるように見え
原因が分からないのでご教示いただけますと幸いです...
※参考にしたサイト
http://itmemojp.blogspot.com/2012/10/rails.html
completed200
1Started GET "/new_posts/search?area_id=4" for ::1 at 2019-09-16 11:35:44 +0900 2Processing by NewPostsController#search as JSON 3 Parameters: {"area_id"=>"4"} 4通過:new_posts/search 5 Rendering new_posts/search.js.erb 6 Prefecture Load (0.4ms) SELECT `prefectures`.* FROM `prefectures` WHERE `prefectures`.`area_id` = 4 7 ↳ app/views/new_posts/search.js.erb:1 8 Rendered new_posts/search.js.erb (3.0ms) 9Completed 200 OK in 379ms (Views: 377.8ms | ActiveRecord: 0.4ms)
routes.rb
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root 'all_posts#all_post' get 'post_detail', to: 'post_details#post_detail' resources :new_posts do collection do get 'search' end end end
new.html.erb
<div class="form_body"> <%= form_for(@posts, url: new_posts_path) do |f| %> <div class ="pulldown">場所: <%= f.collection_select(:id, Area.all, :id, :area) %> <%= render 'new_posts/search', {:f => f} %> </div> <br> 下記省略
_search.html.erb
<%= f.select(:prefecture_id, @prefectures, :id, :prefecture) %>
new_post.js
'use strict' $(document).ready(function() { $("p").text("jQuery稼働てすと(稼働中)"); $('#post_id').on('change', function() { var area_id = $('option:selected').val(); console.log(area_id); $.ajax({ type:'GET', url:'/new_posts/search', data: {area_id: area_id}, dataType:'json' }); console.log('Ajax完了'); }); });
new_posts_controller.rb
class NewPostsController < ApplicationController require 'pry' def new @posts = Post.new @prefectures = Prefecture.where(area_id: '1') respond_to do |format| format.html # new.html.erb format.json { render json: @posts } end end def create @Post = Post.new(post_params) @Post.save! redirect_to root_path end def search @prefectures = Prefecture.where(area_id: params[:area_id]) area_id = params[:area_id] puts '通過:new_posts/search' render end
search.js.erb
$("#post_prefecture_id").html("<%= escape_javascript(options_for_select(@prefectures.map{ |prefecture| [prefecture.id, prefecture.prefecture] })) %>");
回答1件
あなたの回答
tips
プレビュー