簡體   English   中英

Ruby on Rails-嵌套屬性不起作用

[英]Ruby on Rails - Nested attributes not working

我有兩個簡單的模型:

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

我正在嘗試使用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的地址。

但是我不得不修改我的模型,並從community.rbvalidates方法中刪除:address

那么如何使accepts_nested_attributes_for工作呢?

我認為您正在使用Rails5。此問題是由於Rails 5中的功能更改引起的。有關更多信息, 請閱讀this 您應該嘗試添加optional: true belongs_to關系。 像這樣。

class Address < ApplicationRecord
    belongs_to :community, optional: true
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM