У меня есть эти две простые модели:Рубин на Rails - Вложенные атрибуты не работает
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
И
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
Я пытаюсь создать несколько заглушек Communities с помощью 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
Но я всегда получаю:
ActiveRecord::RecordInvalid: Validation failed: Address community must exist
PS: Также попытался использовать "community.create_address" и другие вещи. Чтобы только так, как я мог бы получить его на работу было:
- Сохранение сообщества (без адреса)
- Сохранение адреса ссылающийся community_id.
Но мне пришлось взломать мою модель и удалить :address
из метода validates
в community.rb.
Так как я могу сделать принимаетs_nested_attributes_for работает?
Даже если у меня нет адреса без сообщества? –