0

I'm working on a Ruby on Rails application using Rails 3.2 and ruby 1.9.3. I'm using mongodb with mongoid and I would like to ask you if there is a possibility to implement a single "fields for" for a single object in the one-to-many relationship.

class House
  include Mongoid::Document

  embeds_many :rooms
  accepts_nested_attributes_for :rooms

  field :city, type: String

end

class Room
  include Mongoid::Document

  embedded_in :house

  field :color, type: String
  field :area, type: String

end

I would like to do a View where you can add more Rooms, while you are creating a House. For instance,

- form_for @house do |f|

    = f.input :city

    (show the list of rooms I am creating)

    - f.fields_for :rooms, @house.rooms.build do |builder|
         = builder.input :color
         = builder.input :area

The behaviour should be like the next:

You can create multiple rooms in the same form and when you finish to add these rooms, submit the house form in order to save the home with the rooms.

Thanks in advance people

jmolina
  • 259
  • 3
  • 12
  • Assuming room has a house_id attribute I believe what you have should work (although you may need to pluralize room inside the House model and in the fields_for line?)... I might be misunderstanding the question though... – user3334690 May 21 '14 at 14:38
  • What I want to do is create a room, submitting the room form, but not the house form. If I try to fill in the room form and then submit it, and I do the same process again, wihout submitting house form, I will overwrite the last room, not adding a new one. – jmolina May 21 '14 at 16:24
  • what does your controller look like? – user3334690 May 21 '14 at 16:37
  • accepts_nested_attributes_for should also be plural I think, i.e. accepts_nested_attributes_for :rooms – user3334690 May 21 '14 at 16:44
  • My controller should have a new and create method for rooms and for the house. What I really want to say is that: It is possible to create multiple rooms in a house without saving the house, and at the end to the creating rooms process, save the house? or I have to fill a form for a room, submit the form for the room and the house and then add another form for adding a new room? – jmolina May 22 '14 at 07:35
  • well you could add additional rooms to the page (via some js) and then submit all of the rooms and the house at once... see this [question](http://stackoverflow.com/questions/4232367/rails-railscasts-nested-complex-forms) for an explanation... though the question does not have a good answer the question itself is pretty much exactly what you are looking for I think – user3334690 May 22 '14 at 12:43

0 Answers0