シェルスクリプトマガジン

特集1 Ruby on Rails入門(Vol.83記載)

著者:安川要平

本特集では、地図アプリの作成を題材に、Webアプリケーションフレームワーク「Ruby on Rails」によるWebアプリの開発手順を紹介します。説明は、米GitHub社が提供するクラウド開発環境「GitHub Codespaces」を使って進めます。そのため、Webブラウザさえあれば紹介する手順を確認できます。Webブラウザだけで体験できるようになった最新のRubyとRailsを一緒に触ってみましょう。

シェルスクリプトマガジン Vol.83は以下のリンク先でご購入できます。

図15 「app/models/spot.rb」ファイルに追加する1行

class Spot < ApplicationRecord
  has_one_attached :photo
end

図16 「app/views/apots/_form.html.erb」ファイルに追加する記述

(略)
  <div>
    <%= form.label :name, style: "display: block" %>
    <%= form.text_field :name, readonly: false %>
  </div>
  <div>
    <%= form.label :photo, style: "display: block" %>
    <%= form.file_field :photo, readonly: false %>
  </div>
  <div>
    <%= form.submit %>
  </div>
<% end %>
(略)

図18 「app/controllers/spots_controller.rb」ファイルに追加する記述

(略)
    # Only allow a list of trusted parameters through.
    def spot_params
      params.require(:spot).permit(:lat, :lng, :name, :photo)
    end

end

図19 「app/helpers/spots_helper.rb」ファイルに追加する記述

(略)
    html << "<strong>Name:</strong> #{spot.name}<br />"
    if spot.photo.attached?
      html << "<strong>Photo:</strong> #{image_tag(spot.photo, width: '100%')}<br />"
    end
    return html.html_safe
  end
end

図25 提供されるサンプルデータの内容

[
  {
    id:    "1037",
    lat:   "35.7087568",
    lng:   "139.7196777",
    name:  "早大で入試「一般選抜」がスタート"
    photo: "https://localmap.jp/images/takadanobaba/1037.jpg",
    url:   "https://takadanobaba.keizai.biz/headline/1037/",
  },
(略)
]

図26 サンプルデータを取得して画面に表示するコード

require 'net/http' # 'net-http'ではないことに注意
uri = URI('https://localmap.jp/scaffold.json')
response = Net::HTTP.get(uri)   # ファイルを取得 
map_data = JSON.parse(response)	# 結果を変数に格納
p map_data # 画面に表示	

図28 サンプルデータを自動入力するコード

require 'net/http'
uri = URI('https://localmap.jp/scaffold.json')
response = Net::HTTP.get(uri)
map_data = JSON.parse(response)

# 各スポットのデータ(map)に対して以下のコードを実行
map_data.each do |map|
  # 新規スポットにサンプルデータを入力
  spot = Spot.new(
    lat:  map['lat'],
    lng:  map['lng'],
    name: map['name'],
  )
  # 新規スポットに画像を添付
  spot.photo.attach(
    io: URI.open(map['photo']),
    filename: map['id'] + '.jpg',
  )
  # 新規スポットをDBに保存
  spot.save
end