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

时间:2017-01-04 18:22:45

标签: ruby-on-rails ruby

我有两个简单的模型:

var tableRow = $("td").filter(function () {
var x = $('.search2').val();
return $(this).text() === x;
}).closest("tr");


$(".search").click(function() {
        $('tr').not(tableRow).hide();
});

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

我尝试使用seed.rb创建一些存根社区:

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

但我总是得到:

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

    @communities += 1
  end

PS:还尝试使用&#34; community.create_address&#34;和其他东西。 我只能这样才能让它发挥作用:

  • 保存社区(没有地址)
  • 保存地址引用community_id。

但我必须破解我的模型并从 community.rb 中的ActiveRecord::RecordInvalid: Validation failed: Address community must exist 方法中移除:address

那么如何才能使 accepts_nested_attributes_for 工作?

1 个答案:

答案 0 :(得分:1)

我认为您正在使用Rails 5.此问题是由于Rails 5中的功能更改。有关详细信息read this。 您应该尝试将optional: true添加到belongs_to关系。像这样。

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