LoginSignup
7
13

More than 5 years have passed since last update.

Googleフォームで入力された情報をrailsのデータベースに保存する

Posted at

Googleフォームの情報をrailsのデータベースに送りたい

Googleフォーム使うときはスプレッドシートに集計するパターンはあるある。
今回はRailsアプリケーションのデーターベースに保存してみたので自分用に簡単にメモ。
目的としては入力されたユーザーの住所情報を保存すること。
このときLocationはstring型の:addressを持っている、データベースはpostgreSQL。

ルーティングでPOST先のURLを用意して、スクリプトでPOST先のURLにfetchしてあげる。
そうしてPOSTで送られてきた内容をコントローラで処理してLocationに保存
といった流れになっている。

Googleフォームのスクリプト

実際のフォームとスクリプトエディタの中身がこちら
このとき、フォームの質問内容を 住所を入力してください としている

フォーム内容

スクリーンショット 2017-04-16 10.40.20.png

スクリプトエディタ

post_form.js
function post_contents(e) {
    var itemResponses = e.response.getItemResponses();
    var address = '';
    for (var i = 0; i < itemResponses.length; i++) {
        var itemResponse = itemResponses[i];
        var question = itemResponse.getItem().getTitle();
        var answer = itemResponse.getResponse();
        if (question == '住所を入力してください'){
            address = answer;
        }
    }

    var data =
        {
            "User":
                {
                    "address": address
                }
        };

    var payload = JSON.stringify(data);

    var options =
        {
            "method"  : "POST",
            "payload" : payload,
            "contentType" : "application/json",
            "followRedirects" : true,
            "muteHttpExceptions": true
        };

    var response = UrlFetchApp.fetch("POST先のURL", options);
    Logger.log(response);
}

Controller (Rails)

CSRF対策を無効にしてます。

locations_controller.rb
class LocationsController < ApplicationController
  protect_from_forgery except: :create

  def create
    location = Location.new(location_params)
    location.save
    render json: {}, status: :ok
  end

  def location_params
    params.require(:user).permit(:address)
  end

end

ちなみにルーティングには

routes.rb
  resources :locations, :only => [:index, :create]

を加えている。

端的に書いてるので
足りない情報あったら教えてください。。

7
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
13