LoginSignup
0
1

More than 3 years have passed since last update.

Rails fields_for体系

Last updated at Posted at 2020-09-04

How to use

Overview

formの中で異なるモデルに値を入力したい時に有効的よん。

Example

Hotelモデルがあります。さらに、Hotelモデルと多対多の関係にあるFeeモデルがあります。これらは、ホテルとホテル予約料金プラン(複数)の関係性ですねー。

ホテル登録フォームがあります。その中には、ホテル予約料金プランを入力するフォームがありますっ。しかし!ここで問題が発生。通常のform_forを使ったフォームではモデルが1つしか設定できません😥

そこで!fields_for登場。form_forに親モデルであるHotelモデルを指定。そして、form_forの中にfields_forを作りFeeモデルを指定。あとは、通常と同様にオプションを指定すれば、フォームにデータを入力できる!

Detail

  • 親モデル(Hotel)にaccepts_nested_attributes_forメソッドを記述
  • fee_attributesをHotelコントローラーのストロングパラメーターに追加

Putting into practice

登場人物
Hotelモデル(親)
Feeモデル(子)

Model
hotel.rb
has_many :fees
accepts_nested_attributes_for :fees
Controller
hotels_controller.rb
def hotel_params
  params.require(:hotel).permit(:name, fee_attributes: [:id])
end
View
hotel.html.erb
<%= form_for @hotel do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>
  <%= f.fields_for :fees do |i| %>
    <%= i.label :hotel_fee1 %>
    <%= i.number_field :hotel_fee %>
    <%= i.label :hotel_fee2 %>
    <%= i.number_field :hotel_fee %>
  <% end %>
  <%= f.submit "upload" %>
<% end %>

(途中)

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