简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM