0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rails プラクティス

Last updated at Posted at 2017-08-05

アソシエーション

accepts_nested_attributes_for

has_oneやhas_manyで関連する子レコードを保存するメソッドの追加

Company
  has_many :addresses
  accepts_nested_attributes_for :addresses, allow_destroy: true
Address
  belongs_to :company

とすると、Companyモデルを保存するタイミングでAddressモデルを作成・更新できる。

addresses_attributes のように _attributes がつけられる。

フォームなどの画面から編集した場合によく使われるが、モデルのみでも使うことができる。

コントローラーではStrong Parameterに追加しておくとよい。

param.require(:company).permit(
   addresses_attributes: [
      :_destroy,   # 削除する場合 trueに設定
      :id,
      :name
   ]
)

ビューの fields_for と組み合わせて使う。

バリデーション

validates のデフォルトバリデータ

RailsAPI:ActiveModel::Validations::ClassMethods

項目名 ヘルパメソッド名 内容
acceptance validates_acceptance_of チェックされているか(同意している)か
confirmation validates_confirmation_of メールやパスワードが一致しているか
exclusion validates_exclusion_of
format validates_format_of
inclusion validates_inclusion_of
length validates_length_of
numericality validates_numericality_of
presence validates_presence_of
uniqueness x

オプション

項目名 内容
on バリデーションを有効にするときコンテキスト.
valid? や save? メソッド時の contextオプションで指定する.
省略時は :create, :update など。
on: [:create, :update]
if バリデーションを有効にするときの条件 if: :password_required?
unless バリデーションを無効にするときの条件
allow_nil nil を通すか allow_nil: true
allow_blank 空を通すか allow_blank: true
strict エラー時に例外を投げるか strict: false

コントローラとビュー

RailsGuides:Action Controller の概要
RailsGuides:レイアウトとレンダリング

view_context

ActionView のインスタンス。コントローラ中のデフォルトのビュークラス。

ビューの表示は ActionController::Base#render が行っている

render_to_string

出力結果をブラウザに返さずに文字列を返す

sessions

セッションを取得。ハッシュで入ってくる。

session[:foo]
session[:foo] = "bar"

cookies

クッキーの情報を取得。ハッシュで入ってくる

ビュー

ローカル変数を使う

インスタンスの変数のかわりにローカル変数を使う場合

def index
  render "index", foo: 'bar'
end

コンソール

ソースを再読み込みする

development環境で開発中に読み込み直す場合

$ rails c
pry> reload!

テスト

JavaScript

Rspec + Capybara + ドライバ

selenium

Xvfb を使って selenium を起動する

capybara-webkit

headless ドライバ. Qt が必要.

poltergeist

PhantomJS を capybara で使うドライバ. Xvfb が不要.

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?