Rails-子对象的表单

时间:2018-09-19 17:43:16

标签: ruby-on-rails ruby forms activerecord

我对Rails表单有点困惑。我知道有嵌套的表单,但是我还需要其他东西。我认为。

所以,我有模特在地板和房间。每个楼层都有许多房间,每个房间都属于一个楼层。 (1-N关联)

在每个楼层上,我都有按钮来添加新房间。 (以表格形式打开模式)。

如何为该房间关联地板创建表格?


查看:

function changeDetected() {
    name = $('#inputNome').val()
    cpf = $('#inputCPF').val()
    phone = $('#inputPhone').val();
    email = $('#inputEmail').val();

    if(email.length > 0) {
        $('#eula').removeAttr('disabled');
    }
    else {
        $('#eula').attr('disabled', 'disabled');
    }

    if ((name.length > 0) && (cpf.length > 0) && (phone.length > 0)) {
        //The rest of your validation logic
    }
}

型号:

<% @floors.each do |floor| %>
  <div class="card">
    <div class="card-content">
      <span class="card-title"><b> <%= floor.name %></b></span>
      <div class="row">
      <% floor.rooms.each do |room| %>
          <div class="input-field col s3 l3">
            <div class="card">
              <div class="card-content">
                <span class="card-title"><b> <%= room.name %></b></span>
              </div>
            </div>
          </div>
      <% end unless floor.rooms.nil?%>
        <a class="waves-effect waves-light btn modal-trigger" style="float: right" href="#modal2">Add room</a>
      </div>
    </div>

控制器:

class Floor < ApplicationRecord
  has_many :rooms
  accepts_nested_attributes_for :rooms
end

class Room < ApplicationRecord
  belongs_to :floor
end

1 个答案:

答案 0 :(得分:0)

因此,您要为现有楼层创建房间,则不能使用accepts_nested_attributes_for。相反,您可以将{em> nested resources 与form_for一起使用,为该楼层创建一个空间,

<%= form_for [floor, @room] do |f| %>
  --- code---
<% end %>

floor_controller#index中添加@room = Room.new,并在routes.rb中添加以下内容

#routes.rb
resources :floors do
  resources :rooms, only: [:create]
end
相关问题