例如,我有以下模型:
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(addressable_id
和addressable_type
)不存在时,即使我试图在类的方法中添加它,它也拒绝并且不保存数据。main_address_attributes=(attributes)
Company
每当我尝试使用以上参数保存它时,都会出现此错误:
Main address addressable can't be blank
我该如何解决?
万一belongs_to
你有类似的东西:company
与address
(通过main_address_id
)有关,而这与通过多态与另一个(Company
或Person
)有关addressable
。
例如,您可以更改:
has_one :address, as: :addressable
到:
has_many :address, as: :addressable
然后添加到您的Address
:
enum address_type: [:primary, :secondary]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句