简体   繁体   English

如何为具有嵌套属性的多态模型保存一个longate_to关联?

[英]How to save a belongs_to association for a polymorphic model with nested attributes?

For example I have these models: 例如,我有以下模型:

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

I am trying to save the Company with nested attributes, you can assume this as the params: 我正在尝试使用嵌套属性保存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"}}

This doesn't work as it rejects and doesn't save data when addressable( addressable_id and addressable_type ) for main_address isn't present, even when I am trying to add it in main_address_attributes=(attributes) method in Company class. 这不起作用,因为当main_address的 addressable( addressable_idaddressable_type )不存在时,即使我试图在Company类的main_address_attributes=(attributes)方法中添加它,它也拒绝并且不保存数据。

Whenever I try to save this with the above params I get this error: 每当我尝试使用上述参数保存时,都会出现此错误:

Main address addressable can't be blank

How do I resolve this? 我该如何解决?

In case with belongs_to you will have something like: company related to address (through main_address_id ) which in return is related to another( Company or Person ) through polymorphic addressable . 如果使用belongs_to您将拥有类似以下内容的信息:与address相关的company (通过main_address_id ),而该address通过多态addressable与另一个( CompanyPerson )相关。

As example you could change: 例如,您可以更改:

has_one :address, as: :addressable

to: 至:

has_many :address, as: :addressable

and then add to your Address : 然后添加到您的Address

enum address_type: [:primary, :secondary]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM