CNuts CNuts - 4 days ago 3
Ruby Question

Two different classes using accepts_nested_attributes of one class

I have a class Addresse where Organismereferent and Organisme have a

has_many
belongs_to
relationship with. Also Organismereferent and Organisme can
accepts_nested_attributes_for :addresses


My problem is when I only had the Organismereferent class everything was working fine and I was able to create a new Organismereferent with an addresse but as soon as I created and added the same relation to Organisme , they both stopped working without giving any error message I only get this in the console:
enter image description here

My model:

class Organismereferent < ApplicationRecord
has_many :addresses
has_many :referents
accepts_nested_attributes_for :addresses
end

class Organisme < ApplicationRecord
has_many :addresses
accepts_nested_attributes_for :addresses
end

class Address < ApplicationRecord
belongs_to :organismereferent
belongs_to :organisme
end


Controller for Organisme

def new
@organisme = Organisme.new
@organisme.addresses.build
end

def create
@organisme = Organisme.new(organisme_params)
@organisme.status = true
@organisme.save
redirect_to @organisme
end

private
def organisme_params
params.require(:organisme).permit(:nom, :telephone, :courriel, :fax, addresses_attributes: [:id, :no_civique, :rue, :ville, :province, :etat, :code_postal])
end


Controller for Organismereferent:

def new
@organisme = Organismereferent.new
@organisme.addresses.build
end

def create
@organisme = Organismereferent.new(organisme_params)
@organisme.active = true
@organisme.save
redirect_to @organisme
end

private
def organisme_params
params.require(:organismereferent).permit(:nom_organisation, :bureau, :telecopie, :courriel, :site_web, addresses_attributes: [:id, :no_civique, :rue, :ville, :province, :etat, :code_postal])
end


I'm not sure what else information might be important so I'll be glad to add anything.

Answer

Try to change address model like

class Address < ApplicationRecord
  belongs_to :organismereferent, optional: true
  belongs_to :organisme, optional: true
end