如何使用嵌套属性保存多态模型的belongs_to关联?

时间:2014-08-31 16:02:36

标签: ruby-on-rails activerecord ruby-on-rails-4 polymorphic-associations

例如我有这些模型:

class Person < ActiveRecord::Base
  # attributes: id, name
  has_one :address, as: :addressable
  accepts_nested_attributes_for :address
end

class Company < ActiveRecord::Base
  # attributes: id, name, main_address_id
  has_one :address, as: :addressable
  belongs_to :main_address, class_name: 'Address', foreign_key: :main_address_id

  accepts_nested_attributes_for :main_address

  def main_address_attributes=(attributes)
    puts '='*100
    puts attributes.inspect
    self.build_main_address(attributes)
    self.main_address.addressable_id = self.id
    self.main_address.addressable_type = self.class.to_s
    puts self.inspect
    puts self.main_address.inspect
  end
end

class Address < ActiveRecord::Base
  # attributes: id, address1, address2, city_id,..
  belongs_to :addressable, polymorphic: true
  validates :addressable_id, :addressable_type, presence: true
end

我正在尝试使用嵌套属性保存Company,您可以将其视为参数:

{"name"=>"Test Company", "email"=>"", "display_name"=>"Company pvt ltd", "description"=>"Company desc", "founded_in"=>"2014-08-05", "website"=>"", "main_address_attributes"=>{"address1"=>"My address1", "address2"=>"My address2", "city_id"=>"10"}}

main_address 不可寻址(addressable_idaddressable_type)时,这不起作用,因为它拒绝并且不会保存数据现在,即使我试图在main_address_attributes=(attributes)类的Company方法中添加它。

每当我尝试使用上述参数保存时,我会收到此错误:

Main address addressable can't be blank

如何解决此问题?

1 个答案:

答案 0 :(得分:0)

如果使用belongs_to,您会有类似companyaddress(通过main_address_id)相关的内容,而这些内容与另一个相关(CompanyPerson)通过多态addressable

例如你可以改变:

has_one :address, as: :addressable

为:

has_many :address, as: :addressable

然后添加到您的Address

enum address_type: [:primary, :secondary]