0

I have this two simple models:

class Address < ApplicationRecord
  belongs_to :community

  geocoded_by :full_address

  validates :address, :city, :province, :country, presence: :true

  validates :postalcode, presence: true, postalcode: true

  after_validation :geocode

  def full_address
    [address, province, postalcode, country].compact.join(', ')
  end
end

And

class Community < ApplicationRecord
  has_one :address, dependent: :destroy

  accepts_nested_attributes_for :address

  has_many :community_people, dependent: :destroy

  has_many :people, through: :community_people, source: :user

  validates :name, :address, :administrators, presence: true  
  # ...
end

I'm trying to create some stub Communities using a seed.rb:

def self.create_community(administrators: [], residents: [], address: {})
     Community.create(
        name:  Faker::Name.name,
        administrators: administrators,
        residents: residents,
        address_attributes: address
      )

    @communities += 1
  end

But I always get:

ActiveRecord::RecordInvalid: Validation failed: Address community must exist

PS: Also tried using "community.create_address" and other things. To only way I could get it to work was:

  • Saving Community (with no address)
  • Saving Address referencing community_id.

But I had to hack my Model and remove :address from the validates method in community.rb.

So how can I make accepts_nested_attributes_for work?

1 Answer 1

1

I think you are using Rails 5. This issue is because of feature change in Rails 5. For more info read this. You should try adding optional: true to belongs_to relationship. Like this.

class Address < ApplicationRecord
    belongs_to :community, optional: true
end
Sign up to request clarification or add additional context in comments.

1 Comment

Even though I cant have an Address without a Community?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.