Nested Forms with belongs_to association

tl;dr: nested attributes isn’t setting the belongs_to association

I have these two models right now:

class Organization < ActiveRecord::Base
has_many :groups
belongs_to :main_group, :class_name => Group.name, :foreign_key =>
:main_group_id, :autosave => true

validates_presence_of :main_group

accepts_nested_attributes_for :main_group, :allow_destroy => true
end

class Group < ActiveRecord::Base
belongs_to :organization, :autosave => true

validates_presence_of :organization
end

I want to create a nested form that will create a new User along with
the
Organization along with a new Group. My form code is the following:
<%= form_for(@user) do |f| %>
<%= f.label :email, “Email Address” %>

  <%= fields_for :organization, @organization do |org_f| %>
    <%= org_f.label :name, "Organization Name" %>
    <%= org_f.text_field :name %>
    <% if org_f.object.new_record? %>
      <%= org_f.fields_for :main_group do |main_f| %>
        <%= main_f.label :name, "Your Org's Main Group" %>
        <%= main_f.text_field :name %>
      <% end %>
    <% end %>
  <% end %>

<% end %>

Here’s my Controller’s action code that’s giving me errors:
def create
@user = User.new(params[:user])
if !params[:secret].to_s.empty?
@user.accept_invitation(params[:organization][:id],
params[:secret])
@organization = @user.organizations.first || Organization.new
else
@organization =
@user.organizations.build(params[:organization].slice!(:id))
@organization.main_group.organization = @organization
end

def create
if !params[:secret].to_s.empty?
@user.accept_invitation(params[:organization][:id],
params[:secret])
@organization = @user.organizations.first || Organization.new
else
@organization =
@user.organizations.build(params[:organization].slice!(:id))
# If I comment out the following line, it’ll break
# @organization.main_group.organization = @organization
end
end

My question is: is there a more elegant way to set the #main_group’s
association to the organization than the commented line above?

Thanks everyone.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs