Skip to content

Instantly share code, notes, and snippets.

@tkawa
Created January 13, 2014 02:59
Show Gist options
  • Save tkawa/8394031 to your computer and use it in GitHub Desktop.
Save tkawa/8394031 to your computer and use it in GitHub Desktop.

RailsGirls, More! #11 2014.01.12

データ保存用モデルをつくる

短い文字列はstring(省略可)、長い文字列はtext名前:型の形で指定する。

$ rails g model interview url question:text answer:text

他には整数integer、true/falseの型boolean、時間datetimeなどがある。

マイグレーションファイル db/migrate/20140112032552_create_interviews.rb が生成される。

空になることを禁止したいならnull: falseをつけ足す。
ユニークであることを保証したいならadd_index :interviews, :url, unique: trueの行を足す。

マイグレーションファイルが完成したら$ rake db:migrateを忘れずに。(忘れて$ rails sするとエラーになる)

コントローラをつくる

コントローラ名は、CRUDできる「もの」(名詞)の複数形

  • Create
  • Read (index, show)
  • Update
  • Destroy

動作・操作を主体にしたいときは、動詞のing形、過去分詞形もあり
crawlは名詞もあったからcrawlsでもよかったかも。

$ rails g controller Crawlings

class CrawlingsController < ApplicationController
  def index
  end
  def create
  end
end

メソッド名(index, create)は、上のCRUDに対応している。

ルーティングを設定する

URLのパス名(/crawlings)とCrawlingsControllerを結びつける。

config/routes.rb

resources :crawlings

ビューをつくる

場所は app/views/crawlings/index.html.erb

<form method="post">
ID:<input type="text" name="user_name" />
<input type="submit" value="送信" />
</form>

method="get"のときはindex, method="post"のときはcreateに対応する。

name="user_name"の値は、コントローラ内でparams[:user_name]で取得できる。

モデル(データベース)への保存

Interview.create!(
  url:        page.url.to_s,
  question:   question,
  answer:     answer,
  created_at: date
)

createにすると、もし失敗してもそのままスルー(falseを返す)。create!の場合は失敗すると止まる。

モデル(データベース)のその他の操作

既存のものから1個検索するfind_by

Interview.find_by(url: 'http://...')

find_by!にすると、もしなければ止まる。

既存のものから複数検索するwhere

Interview.where(url: 'http://...')

この場合urlはユニークなので意味がないけど。

数を数えるcount

whereと組み合わせることも可能。

Interview.count
Interview.where(url: 'http://...').count

コントローラの処理後

もしアクションメソッドと同名のビューファイルがある場合は、それが出力される。(indexがその例)

redirect_toを書くと、指定したURLに302でリダイレクトされる。

redirect_to crawlings_path, notice: '保存できました!'

処理結果を伝えるメッセージとして、noticealertがビューで使用可。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment