2019/2/10学習記録

form_withについて

form_forとform_tagを統合したもの。rails5.1から使用可能。
form_with model: relatedobject, local: true do |f| 
f.label~

等のお馴染みの書き方で使用する

= form_with scope: :session, local: true do |f|

scopeは送信されたパラメータをコントローラーでグループ化するもの。
この書き方だとsession { email: hoge@exmaple.com } のような形で送られる。

 

プレフィックスについて

名前付きルートのこと。
users_pathみたいな相対パス表記のもの。

 

authenticateメソッド

has_secure_passwordを追加した際に使用可能となったパスワード認証メソッド。引数で受け取ったパスワードをハッシュ化してパスワードダイジェストの
内容と付き合わせ認証を行う。

 

フィルタについて

class SessionsController < ApplicationController
skip_before_action :login_required

このように記載すればbefore_actionをスキップできる。多くのcontrollerに適用するフィルタをapplication controllerに記載し、適用押したくないcontrollerにはこれを使用すると便利。

 

マイグレーションについて

ex)一対多の関連づけのためのmigration

class AddUserIdToTasks < ActiveRecord::Migration[5.2]
def up
execute "DELETE FROM tasks;"
add_reference :tasks, :user, null: false, index: true
end

def down
remove_reference :tasks, :user, index: true
end
end

add_reference :tablename, :reference, option: 

add_reference(テーブル名, リファレンス名 [, オプション])

 

upはバージョンを上げる時でdownはバージョンを下げる時(戻す時)適用される。migrationを書く際は書く必要がある。でないと戻せなくなる。
change methodでテーブルを作成した時は、戻すさいの処理もrails側で処理してくれるので書く必要はない。

 

Active Record関連

データの検索をするときの考え方

User.where(admin: true).first

Userの部分は起点
whereの部分は絞り込み条件
firstの部分は実行部分

 

scopeの記述について

scope :resent, -> {order(created_at: :desc)}

このような形でモデルにlamdaでmethodを記述する事で、よく使う処理をmethodで使用できるようになり便利な上に煩雑なcontrollerの処理をスッキリさせる事ができる。

 

参考:Ruby on rails5 速習実践ガイド

railsdoc.com

techracho.bpsinc.jp