0
0

More than 3 years have passed since last update.

Rails form_with 解説してみる

Posted at

どうもチャンクノです。
今回は前回の記事で書いたform_withの解説をしてみようかなと思います。
間違ってる部分ありましたら修正するのでコメントにて伝えてください。

はい、では以下のコードをご覧ください。

<%= form_with model: [:user, current_user], url: user_user_profile_path, local: true do |f| %>
  <%= f.fields_for :user_profile, current_user.user_profile || current_user.build_user_profile do |profile| %>
    <%= profile.text_field :name %>
  <% end %>
  <%= f.fields_for :user_address, current_user.user_address || current_user.build_user_address do |address| %>
    <%= address.text_field :zipcode %>
  <% end %>
 <%= f.submit %>
<% end %>

まずは

<%= form_with model: [:user, current_user], url: user_user_profile_path, local: true do |f| %>

この部分ですね。
model: [:user, current_user]の[:user]の部分はネームスペースを示しています。(多分)
ネームスペースを使っていない場合は、model: current_user でおけです。
current_userの部分はモデルのインスタンスが入ります。
今回はrequire(:user)なのでcurrent_userでオッケー。
requireで指定したモデルのインスタンス変数を書くんだと覚えておけば大丈夫だと思います。

そして、form_withは model: [:user, current_user] この部分でパラメーターを送るpathを自動的に判断します。
現状だとこれがどんなパスになるかわかりますか?
正解はuser_user_pathです。
しかし今回はそんなpathは存在しないのでこのままだとエラーになります。
そこでどうするか、urlの出番です。
今回使いたいのはUser::UserProfilesControllerです。
なので model: [:user, current_user], url: user_user_profile_path こうして明示的にpathを指定してあげてください。
そうすると指定したpathのコントローラーにパラメーターが飛んでいき、updateが動いて更新してくれます。
めでたいですね🌞
local: trueはつけていない場合ajaxによる送信と見なされてしまいす。
ajaxなんて使ってない!!という場合はlocal: trueをつけましょう。

次はこの部分について。

<%= f.fields_for :user_profile, current_user.user_profile || current_user.build_user_profile do |profile| %>

f.fields_forの後には子モデルの名前を書きます。
ですがこのままだとeditページには何も表示されないし、保存もできないので
current_user.user_profile || current_user.build_user_profile
これがついています。
user_profileが存在すればそれを表示し、なければbuildしてくれる処理になっています。
この処理をコントローラーに書くか、viewに書くか、どちらがいいのかは正直わかりません🙇‍♂️
form_withについてはこんなところでしょうか🤒
これだけ理解しておけば基本的なcrudで困ることはないと思います!
何かあったらまた追記します!!

それでは今日はこの辺で!
皆様よきプログラミングライフを🙏

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