first_or_initializeとfind_or_initialize_by
3640 ワード
この2つのメソッドは同じような用途で使えますが、どのような使い分けをすればいいのかをまとめてみました。
find_or_initialize_by
# File activerecord/lib/active_record/relation.rb, line 222
def find_or_initialize_by(attributes, &block)
find_by(attributes) || new(attributes, &block)
end
find_by
とnew
の引数に同じattributes
が渡される。
なので、下記のようなJOINしたテーブルを検索条件に含めるとActiveRecord::AssociationTypeMismatch
の例外が発生する。
A.joins(:bs).find_or_initialize_by(bs: {id: 1})
first_or_initialize
# File activerecord/lib/active_record/relation.rb, line 161
def first_or_initialize(attributes = nil, &block)
first || new(attributes, &block)
end
first
がない場合、first_or_initailize
の第一引数でオブジェクトを初期化するので、下記のように検索した条件とは別にAttributeで初期化することができる。
A.where(name: "foo").first_or_initialize(name: "bar")
引数を省略すると、もちらんAttributeはなにも設定されないまま初期化される。
まとめ
-
join
をして、検索条件にjoin
したテーブルが含んでいる場合はfirst_or_initialize
- 検索条件と初期化したいオブジェクトのAttributeと違う場合は
first_or_initialize
、同じ場合はfind_or_initialize_by
参考リンク
Author And Source
この問題について(first_or_initializeとfind_or_initialize_by), 我々は、より多くの情報をここで見つけました https://qiita.com/kouyaf77@github/items/c1cffbee7c8f189cc15e著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .