Ruby on Rails: accept nested attributes for parent and not child records?

There can be many People in my Rails Users application, which, in turn, can belong (but not necessarily) to Organisations .

In short, this is:

 Users --< People >-- Organisations 

Now it would be nice to be able to create new organizations from the way people are represented in some way. He 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 does not work, because the Organization is not a child of Person.

Is there any other way to implement this?

Thanks for any help.

+4
source share
1 answer

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

Suppose you want to show the Organisation form for an already saved Person . Then

Create an organization in your PeopleController#show method

 @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 like this and it worked :) Ive done the gist including fragments. Please go to https://gist.github.com/3841507 to see how it works.

+4
source

Source: https://habr.com/ru/post/1438031/


All Articles