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_bed开发者_开发知识库rooms
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:
>> 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. 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.
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]}) %>
精彩评论