プログラミングと旅と映画の日々

普段はスマホ決済サービスの会社でバッグエンドを担当しているエンジニアです。プログラミングと趣味の映画、株、時々うどんに関してブログを書いていこうと思います。海外ドラマ、クロスバイクも好きです。

【Ruby on Rails5】Faker gemを利用してダミーデータを作成する

f:id:takanori5:20180113103312p:plain


userの一覧画面などを実装した際に

userデータを一件ずつ画面登録していくのは超面倒ですね!



Fakerというgemでダミーデータを作成してしまいましょう。

gemfileに以下を追加

gem 'faker',          '1.7.3'

続いてインストール

$ bundle install

db/seeds.rbに以下のようにループ処理をかく

99.times do |n|
  name  = Faker::Name.name
  email = "example-#{n+1}@railstutorial.org"
  password = "password"
  User.create!(name:  name,
               email: email,
               password:              password,
               password_confirmation: password)

適用

$ rails db:seed

User一覧にダミーデータが登録されました!
f:id:takanori5:20180121160127p:plain

【Ruby on Rails5】tableにインデックスを貼る

f:id:takanori5:20180113103312p:plain

インデックスを張るメリット
 データの読み込み・取得が早くなる。
デメリット
 書き込みの速度が倍かかる。


張り方
コマンドラインで以下のコマンドを実行

rails generate migration add_index_テーブル名_カラム名

すると以下のマイグレーションファイルが作成されます。

class AddIndexToテーブル名 < ActiveRecord::Migration
  def change
    add_index :テーブル名, カラム名#この行を書く
  end
end

最後に

rails db:migrate

を実行

【Ruby on Rails】rails consoleをサンドバッグモードで起動する

f:id:takanori5:20180113103312p:plain
サンドボックスモードで起動する。
このモードで起動するとコンソール自体が一つのトランザクションになるので色々便利

コンソール終了時にデータベースに関する変更をロールバックすることが可能に。

sandboxオプションをつけて起動する方法は以下のコマンド

rals c --sandbox(もしくは--s)


やってみます。

hodzumitakanori-no-MacBook-Air:sample_app hodzumitakanori$ rails c --sandbox
Running via Spring preloader in process 5428
Loading development environment in sandbox (Rails 5.1.2)
Any modifications you make will be rolled back on exit
irb(main):001:0> 


Any modifications you make will be rolled back on exit
(あなたが行った変更は、終了時にロールバックされます)
とメッセージが出ています。

hodzumitakanori-no-MacBook-Air:sample_app hodzumitakanori$ rails c -s
Running via Spring preloader in process 5545
Loading development environment in sandbox (Rails 5.1.2)
Any modifications you make will be rolled back on exit
Cannot read termcap database;
using dumb terminal settings.
irb(main):001:0> User.create(name: "Hozumi", email: "hozu@mail")
   (0.1ms)  SAVEPOINT active_record_1
  SQL (0.5ms)  INSERT INTO "users" ("name", "email", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["name", "Hozumi"], ["email", "hozu@mail"], ["created_at", "2018-01-13 01:30:04.398166"], ["updated_at", "2018-01-13 01:30:04.398166"]]
   (0.1ms)  RELEASE SAVEPOINT active_record_1
=> #<User id: 2, name: "Hozumi", email: "hozu@mail", created_at: "2018-01-13 01:30:04", updated_at: "2018-01-13 01:30:04">
irb(main):002:0> User.all
  User Load (0.3ms)  SELECT  "users".* FROM "users" LIMIT ?  [["LIMIT", 11]]
=> #<ActiveRecord::Relation [#<User id: 1, name: "Hozumi", email: "hozu@mail", created_at: "2018-01-13 01:27:21", updated_at: "2018-01-13 01:27:21">, #<User id: 2, name: "Hozumi", email: "hozu@mail", created_at: "2018-01-13 01:30:04", updated_at: "2018-01-13 01:30:04">]>
irb(main):003:0> exit
   (2.3ms)  rollback transaction

exitでrollbackされました!

【Ruby on Rails】使用するアクションのルーティングだけを設定する方法

f:id:takanori5:20180113103312p:plain


リソースベースのルーティングを使ってroutes.rbファイルに設定を記述すると自動で7つのルーティングが設定されてしまい、邪魔です。

    post_comments GET    /posts/:post_id/comments(.:format)          comments#index
                  POST   /posts/:post_id/comments(.:format)          comments#create
 new_post_comment GET    /posts/:post_id/comments/new(.:format)      comments#new
edit_post_comment GET    /posts/:post_id/comments/:id/edit(.:format) comments#edit
     post_comment GET    /posts/:post_id/comments/:id(.:format)      comments#show
                  PATCH  /posts/:post_id/comments/:id(.:format)      comments#update
                  PUT    /posts/:post_id/comments/:id(.:format)      comments#update
                  DELETE /posts/:post_id/comments/:id(.:format)      comments#destroy

例えば上記のうち、createとdestroyのみルーティング設定したい場合、
以下のようにroutes.rbに設定すればOK

既存の設定

  resources :posts do   	
  	resources :comments
  end

必要なもののみ設定

  resources :posts do   	
  	resources :comments, only: [:create, :destroy]
  end

【Ruby on Rails】RailsのStrong Parametersとは

f:id:takanori5:20180113103312p:plain

Strong ParametersはDBに入れる値を制限することで、不正なパラメータの入力を防ぐ仕組み
rails4 から導入されたようです。

例えば以下のように受け取ったパラメーターを検証せずにDBに直接保存するようにしていた場合、

	def create
		# render plain: params[:post].inspect
		# save
		@post = Post.new(params.require([:post]))
		@post.save
		# redirect
		redirect_to posts_path
	end

f:id:takanori5:20180106103545p:plain

parameterを許可してDB登録するには

①requireでPOSTで受け取る値のキーを設定
②permitで許可するカラムを設定

が必要です。

例:

       params.require(:post).permit(:title, :body)

この検証はよくprivate mehodにまとめられるので
処理を切り出して使いましょう。

【Ruby】キーワード引数の書き方

通常のメソッドの書き方に加えて、
① 定義側で、引数の後にコロンを付ける
② 呼び出し側で、値の前に引数名を書く
とすることで、キーワード引数を持つメソッドを書くことが可能。



■通常の書き方

def buy(item, price, count)
	puts "#{item}を#{count}台のお買い上げです"
	puts "合計金額は#{price * count}円です"
end

#呼び出し
buy("テレビ", 15000, 2)

■キーワード引数版

def buy(item:, price:, count:)
	puts "#{item}を#{count}台のお買い上げです"
	puts "合計金額は#{price * count}円です"
end

#呼び出し
buy(item:"テレビ",price: 15000,count: 2)