0

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:

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

1 Answer 1

1

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]}) %>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.