6
6

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.

accepts_nested_attributes_forを使う時はform_forの第1引数にModelのインスタンスを渡さないといけない

Last updated at Posted at 2014-06-07

こんなModelがあるとする。

class User < ActiveRecord::Base
  has_one :user_detail
  accepts_nested_attributes_for :user_detail, allow_destroy: true
end
user_detail.rb
class UserDetail < ActiveRecord::Base
  belongs_to :user
end

1つのページでuserとuser_detailを同時に更新したい場合に、

user/_form.html.haml
= form_for :user, url: 'update_page_url' do |f|
  = f.text_field :param1
  = f.fields_for :user_detail |df|
    = df.text_field :detail_param_1
  = f.submit

とすると、次ページでuser_detailの値がうまく取れない。

半日くらいハマって、こうしたらうまくいった。。。

user/_form.html.haml
= form_for @user, url: 'update_page_url' do |f|
  = f.text_field :param1
  = f.fields_for :user_detail |df|
    = df.text_field :detail_param_1
  = f.submit

そういうものなんだろうか・・・あとで詳しく調べよう。

6
6
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
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?