LoginSignup
17
14

More than 5 years have passed since last update.

accepts_nested_attributes_forのupdate_onlyについて

Posted at

日本語で触れている記事が全く無かったので、英語の記事だとすぐに飛ばしちゃうような自分みたいな人の為にメモしておく。
下記のように定義されたモデルがあるとする。

class User
  has_one :user_profile
  accepts_nested_attributes_for :user_profile
  # email:string
end

class UserProfile
  belongs_to :user
  # name:string
end

既に作成済みのUserProfileに、@user.update_attributesメソッドでuser_id無しの更新をかけてみる。

> User.last.user_profile
=> #<UserProfile id: 1, name: "絢瀬絵里", user_id: 1, created_at: "2014-03-17 08:46:26", updated_at: "2014-03-17 08:47:28">
> User.last.update_attributes({ user_profile_attributes: { name: "賢い、可愛い、エリーチカ" }})
# UPDATEの後にINSERTが実行される

ログを見て頂くとわかると思うが、元のUserProfileのuser_idをnilに更新して、新規にUserProfileのデータを作成している。
次にupdate_onlyオプションをつけて、同じように実行してみる。

class User
  has_one :user_profile
  accepts_nested_attributes_for :user_profile, update_only: true
end
> User.last.update_attributes({ user_profile_attributes: { name: "KKE!KKE!" }})
# UPDATEが実行される

このようにパラメータに外部キーが存在しない場合の挙動が変わってくる。
update_onlyはデフォルトtrueでもいいような気がしてるけど、何かあるんですかね。

17
14
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
17
14