8
4

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.

デフォルト値が設定されているモデルのreject_ifの指定方法

Posted at

前提

accepts_nested_attributes_forを使ったreject_ifの指定方法において、
以下のように:all_blankを指定すると、該当フォームがすべて空の場合に無視してくれる。

has_many :users
accepts_nested_attributes_for :users, reject_if: :all_blank

課題

デフォルト値が設定されているカラムがあるモデルに対するフォームの場合、
:all_blankを指定すると、「デフォルト値のみ入力されている状態」はrejectできない。

解決策

以下のように指定すると良い。

has_many :users
accepts_nested_attributes_for :users, reject_if: :reject_user

# デフォルト値が設定されているカラム以外が全て空ならreject
def reject_user(attributes)
  attributes.except(:デフォルト値が設定されているカラム名).values.all?(&:blank?)
end

attributesにはフォームの入力値がハッシュ形式で入っているため、
まずは、attributesからデフォルト値が設定されているカラムをexceptで除外する。

次にvaluesでハッシュの値部分のみを配列にして、
その全ての要素に対して、blank?関数を実行する。

all?メソッドは配列の全てに対して、指定したメソッドを実行し、
指定した関数が全ての要素に対してtrueを返せばtrueを、
ある要素が1つでもfalseを返したらfalseを返す関数である。

8
4
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
8
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?