LoginSignup
0
0

More than 3 years have passed since last update.

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

Posted at

要約

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]"

参考

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