Help us understand the problem. What is going on with this article?

railsのフォームヘルパーを使いながらもnameをカスタムする

要約

railsのフォームヘルパー(form_for, fields_for)を使いながらも、結果生成されるname属性をカスタムしたい時があったのでメモ
めったにないと思うけど、すでにフォームヘルパー使わずに書いてあるnewテンプレートがあって、それに対するcreateを別のテンプレートから再利用したくて、こちらはフォームヘルパー使いたいとおもった。

ポイント

  • 第一引数にstring渡せばカスタムできる
  • urlが正しく行かない場合はurlオプションつける
  • stringの最後に[]つければ配列つくれる →objectに対するFormHelper(ここではa)にfields_for :(has_many名)渡せば自動で[0]にしてくれるけど、fやuはobjectに対するものではないので、自力で配列化してやる
= form_for 'my_users', url: my_users_path do |f|
  = f.fields_for 'my_users_attributes[]', @new_my_user do |u|
    = u.fields_for :profiles, @new_profile do |a|
      = a.text_field :content
=> name="my_users[my_users_attributes][][profiles_attributes][0][content]"

参考

https://railsguides.jp/form_helpers.html#フォームヘルパーを使う

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away