- Railsを始めて1ヶ月半でこれ最初に知っておけばもっと楽に綺麗に実装できたのにって思ったものをまとめました。
- あまり深くは説明していませんので、詳細は調べてください。
※ Railsというか、activesupportの機能のものも入っています。
nilガード
変数val
の値が入っていなかった場合のみ空の値を入れたい場合
before
if val.nil?
val = []
end
after
val ||= []
try
変数staffにnilが入っている可能性のある場合
before
staff ? staff.name : 'none'
after
staff.try(:name) || 'none'
find_or_create_by
- findしてなかったらcreateしたい場合
before
name = 'hogehoge'
user = User.find_by(name: name)
user ||= User.create(name: name)
after
User.find_or_create_by(name: 'hogehoge')
concern
- adminしかアクセスできない属性を持っている画面があったとしてその属性をControllerに書きたい場合
before
- 各Controllerごとに書いていくの辛い…
app/controlllers/hoge_fuga_controller.rb
class HogeFugaController < ApplicationController
before_action :authenticate_user!
def index
# 実装
end
private
def require_admin!
if current_user.nil? || !current_user.admin?
redirect_to root_path, notice: '権限ない旨のメッセージ'
end
end
end
after
- 処理と属性が分かれてすっきり
app/controlllers/hoge_fuga_controller.rb
class HogeFugaController < ApplicationController
include Concerns::AdminAccessible
def index
# 実装
end
...
end
app/controllers/concerns/admin_accessible.rb
module Concerns
concern :AdminAccessible do
included do
before_action :require_admin!
private
def authenticate_user!
if current_user.nil? || !current_user.admin?
redirect_to root_path, notice: '権限ない旨のメッセージ'
end
end
end
end
end
Model内からの検索
- 会社に紐づく社員を社員IDで紐付けを行いたい場合
before
Staff.find_by(company_id: params[:company_id], id: params[:id])
after
@company.staff.find(params[:id])
simple_form
- viewにてformを生成する時
※ 以下以外にもエラーメッセージの処理とか色々よしなにやってくれるので便利
before
- form_for(@user) do |f|
div.field
= f.label :name
= f.text_field :name
div.actions
f.submit
after
- simple_form_for(@user) do |f|
= f.input :name
= f.input :age
= f.button :submit
hash
before
users.map { |v| v[:id] }
after
users.map(&:id)
最後に
- Railsは探せば探す程、便利メソッド、gemがある気がします。
- 他にもこんなのを知っとくといいよ的なやつがあったら教えてください
- 間違いなどありましたら、指摘していただけると嬉しいです。