1
0

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 3 years have passed since last update.

[Rails]field_for 配下の各オブジェクトを取得する方法

Posted at

#課題
fields_for配下の各オブジェクトを取得する方法を知らなかったのでメモ。

<%= form_with model: @user, local: true do |f| %>
  <%= f.text_field :name %>

  <%= f.fields_for :sales do |ff| %>
    <%= ff.text_field :amount, class: 'form-control' %>
  <% end %>
  <%= submit_tag 'submit' %>
<% end %>

上記のようにネストされたフォームで、各子レコードを取得したい。

#結論
ff.object で取れる

コンソールで検証
irb(main):001:0> ff.object
=> #<Sale id: 1, amount: 1000 >

#参考情報
fields_forの上手な使い方
https://qiita.com/kouuuki/items/5daf2b5f34273d8457f7

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?