简体   繁体   English

如何使用accepts_nested_attributes_for手动构建正确的嵌套表单?

[英]How to manually build a correct nested form with accepts_nested_attributes_for?

I'm trying to manually build form fields for a testing purpose. 我正在尝试出于测试目的手动构建表单字段。 I got the following models: 我得到以下模型:

class Bedroom < ActiveRecord::Base
    has_many :booked_bedrooms
    has_many :bookings, :through => :booked_bedrooms
end

class Booking < ActiveRecord::Base
    has_many :booked_bedrooms
    has_many :bedrooms, :through => :booked_bedrooms
    accepts_nested_attributes_for :booked_bedrooms
end

class BookedBedroom < ActiveRecord::Base
    belongs_to :booking
    belongs_to :bedroom
    # fields: bedroom_id, :booking_id
end

When I try the following in a console, booking and the associated booked_bedroom gets saved: 当我在控制台中尝试以下操作时,预订和关联的booked_bedroom将被保存:

>> b = Booking.new({ :booked_bedrooms_attributes => { 0 => { :bedroom_id => 1  }  }  })
=> #<Booking id: nil, start_date: nil, end_date: nil, created_at: nil, updated_at: nil>
>> b.save
=> true
>> b.booked_bedrooms
=> [#<BookedBedroom id: 1, booking_id: 1, bedroom_id: 1, created_at: "2010-06-22 18:55:57", updated_at: "2010-06-22 18:55:57">]

So I built a form like this: 所以我建立了这样一个表格:

<% form_for @booking do |form| %>
<% for bedroom in @available_bedrooms %>

            <%= check_box_tag "booked_bedrooms_attributes[#{bedroom.id}][bedroom_id]", bedroom.id %> <%= bedroom.name %>  
            as
            <%= select_tag "booked_bedrooms_attributes[#{bedroom.id}][booking_type_id]", options_for_select(bedroom.booking_types.map {|p| [p.name, p.id]}) %>
<% end %>
<% end %>

But this won't work. 但这是行不通的。 The booking gets saved, but there are no new BookedBedroom records. 预订已保存,但没有新的BookedBedroom记录。 Can someone tell me what's wrong? 有人可以告诉我怎么了吗?

I know i could use formtastic or some fields_for but I wanted to solve the problem in hardcoded forms, for demonstration purposes. 我知道我可以使用formtastic或某些fields_for,但出于演示目的,我想以硬编码形式解决该问题。

I believe it should be something like 我相信应该是这样

<%= check_box_tag "booking[booked_bedrooms_attributes][][bedroom_id]",
   bedroom.id %>

<%= select_tag "booking[booked_bedrooms_attributes][][booking_type_id]",
   options_for_select(bedroom.booking_types.map {|p| [p.name, p.id]}) %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM