前提・実現したいこと
jQueryとRailsを使用して連動プルダウンを作成中
地方プルダウンで選択した値によって都道府県のプルダウンを変更したいです
controller#searchで取得しているレコードをprefectureのプルダウンに反映させたいです
発生している問題・エラーメッセージ
Controller → Viewに返す時に下記エラーが発生する
NoMethodError (undefined method `to_model' for #<Prefecture::ActiveRecord_Relation:0x000000109ebd20> Did you mean? to_xml):
エラー部分
Viewでプルダウンを選択 → Ajaxで値を受け取りController#searchへ まではできており、searchアクションの@prefecturesで特定IDのレコードは取得できています
おそらくredirect_to @prefecturesが間違っていると思うのですが書き方が分からないので教えていただけますと助かります...
routes.rb
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_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.html.erb
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>◎新規投稿◎</title> <%= javascript_include_tag 'new_post' %> <script type="text/javascript" src="http://code.jquery.com/jquery-2.2.3.min.js"></script> <link rel="stylesheet" type="text/css" href="new_post.css?201610261213"> </head> <body> <p>jQuery 稼働テスト</p> <div class="form_body"> <%= form_for(@posts, url: new_posts_path) do |f| %> <div class ="pulldown">場所: <%= f.collection_select :id, Area.all, :id, :area %> <%= f.collection_select :prefecture_id, @prefectures, :id, :prefecture %> </div> ※下記省略
new_posts_controller.rb
class NewPostsController < ApplicationController require 'pry' def new @posts = Post.new @prefectures = Prefecture.where(area_id: "1") 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]) puts '通過:new_posts/search' redirect_to @prefectures end private def post_params params.require(:post).permit(:prefecture_id, :category_id, :title, :content, :accept_number, :from_age, :to_age) end end
あなたの回答
tips
プレビュー