Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: Accept nested attributes for parent rather than child records?

In my Rails app Users can have many People which in turn can (but don't have to) belong to Organisations.

In short, this:

Users --< People >-- Organisations

Now, it would be nice to be able to create new organisations from within a people view somehow. It tried this:

class Person < ActiveRecord::Base

  attr_accessible :name, :organisation_attributes

  belongs_to :user
  belongs_to :organisation

  accepts_nested_attributes_for :organisation

end

But it's not working because Organisation is not a child of Person.

Is there another way to realise this?

Thanks for any help.

like image 569
Tintin81 Avatar asked Oct 05 '12 15:10

Tintin81


1 Answers

I can see that Person is actually a child of Organisation and its possible to make nested form for parent model also. And you are already using accepts_nested_attributes_for.

Im assuming that you want to show a Organisation form for a already saved person. Then

In your PeopleController#show method build the organisation

@person.build_organisation

And in people/show.html.erb

form_for(@person) do |f|
    f.fields_for(:organisation) do |fo|
        # show the fields of organisation here.
    end
end

It should work.

Update:

I tried something similar and it worked :) Ive made a gist including the snippets. Please follow the link https://gist.github.com/3841507 to see it working.

like image 163
Samiron Avatar answered Oct 03 '22 04:10

Samiron