Search code examples
ruby-on-railsactiverecordruby-on-rails-4polymorphic-associations

How to save a belongs_to association for a polymorphic model with nested attributes?


For example I have these models:

class Person < ActiveRecord::Base
  # attributes: id, name
  has_one :address, as: :addressable
  accepts_nested_attributes_for :address
end

class Company < ActiveRecord::Base
  # attributes: id, name, main_address_id
  has_one :address, as: :addressable
  belongs_to :main_address, class_name: 'Address', foreign_key: :main_address_id

  accepts_nested_attributes_for :main_address

  def main_address_attributes=(attributes)
    puts '='*100
    puts attributes.inspect
    self.build_main_address(attributes)
    self.main_address.addressable_id = self.id
    self.main_address.addressable_type = self.class.to_s
    puts self.inspect
    puts self.main_address.inspect
  end
end

class Address < ActiveRecord::Base
  # attributes: id, address1, address2, city_id,..
  belongs_to :addressable, polymorphic: true
  validates :addressable_id, :addressable_type, presence: true
end

I am trying to save the Company with nested attributes, you can assume this as the params:

{"name"=>"Test Company", "email"=>"", "display_name"=>"Company pvt ltd", "description"=>"Company desc", "founded_in"=>"2014-08-05", "website"=>"", "main_address_attributes"=>{"address1"=>"My address1", "address2"=>"My address2", "city_id"=>"10"}}

This doesn't work as it rejects and doesn't save data when addressable(addressable_id and addressable_type) for main_address isn't present, even when I am trying to add it in main_address_attributes=(attributes) method in Company class.

Whenever I try to save this with the above params I get this error:

Main address addressable can't be blank

How do I resolve this?


Solution

  • In case with belongs_to you will have something like: company related to address (through main_address_id) which in return is related to another(Company or Person) through polymorphic addressable.

    As example you could change:

    has_one :address, as: :addressable
    

    to:

    has_many :address, as: :addressable
    

    and then add to your Address:

    enum address_type: [:primary, :secondary]