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?