使用表单字段创建另一个模型的数量的表单

Form which creates a quantity of another model with form field

我有两个模型,HotelRoom。我想创建一个表格,允许我添加新的酒店和房间,其中指示酒店名称和房间数量。 我知道我应该使用 "nested form",但我很难正确地实现它。

这是我的代码:

HotelsController

class HotelsController < ApplicationController

  def index
    @hotels = Hotel.all
  end

  def new
    @hotel = Hotel.new
  end

  def create
    @hotel = Hotel.new(hotel_params)

    if @hotel.save
      redirect_to @hotel
    else
      render 'new'
    end           
  end

  def show
    @hotel = Hotel.find(params[:id])
  end

  def destroy
    @hotel = Hotel.find(params[:id])
    @hotel.destroy
    redirect_to hotels_url, notice: 'Hotel was successfully destroyed.'
  end

  private

  def hotel_params
    params.require(:hotel).permit(:name, :rooms_count)
  end
end

酒店模型

class Hotel < ApplicationRecord
  has_many :rooms, dependent: :destroy
  accepts_nested_attributes_for :rooms
end

房间模型

class Room < ApplicationRecord
    belongs_to :hotel, optional: true # avoiding rails 5.2 belongs_to error 
end

形式

<%= form_with scope: :hotel, url: hotels_path, local: true do |form| %>
  <p>
    <%= form.label :name %><br>
    <%= form.text_field :name %>
  </p>

  <p>
    <%= form.label :rooms_count %><br>
    <%= form.number_field :rooms_count %>
  </p>

  <p>
    <% form.fields_for :rooms  do |f|%>
      <p>
        **THE CODE**
      </p>
    <% end %>
  </p>

  <p>
    <%= form.submit %>
  </p>
<% end %>

我找到了解决问题的方法。

  def create
    @hotel = Hotel.new(hotel_params)
    @hotel.rooms_count.times do 
      @hotel.rooms.build
    end

    if @hotel.save
      redirect_to @hotel
    else
      render 'new'
    end           
  end

它执行@hotel.rooms.build 的次数与在表格的房间数字段中输入的@hotel.rooms_count 的次数相同。

您忘记了 fields_for 助手上的 "ERB echo sign" (=)。

正确的形式:

  <%= form.fields_for :rooms do |f|%>