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

时间:2010-06-22 19:00:33

标签: ruby-on-rails nested-forms nested-attributes

我正在尝试手动构建表单字段以用于测试目的。我有以下型号:

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

当我在控制台中尝试以下操作时,预订和相关的scheduled_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">]

所以我构建了一个这样的表单:

<% 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 %>

但这不起作用。预订得到保存,但没有新的BookedBedroom记录。有人能告诉我什么是错的吗?

我知道我可以使用formtastic或某些fields_for但我想以硬编码的形式解决问题,以用于演示目的。

1 个答案:

答案 0 :(得分:1)

我认为它应该像

<%= 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]}) %>