[英]How to save a belongs_to association for a polymorphic model with nested attributes?
例如,我有以下模型:
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
)不存在時,即使我試圖在Company
類的main_address_attributes=(attributes)
方法中添加它,它也拒絕並且不保存數據。
每當我嘗試使用上述參數保存時,都會出現此錯誤:
Main address addressable can't be blank
我該如何解決?
如果使用belongs_to
您將擁有類似以下內容的信息:與address
相關的company
(通過main_address_id
),而該address
通過多態addressable
與另一個( Company
或Person
)相關。
例如,您可以更改:
has_one :address, as: :addressable
至:
has_many :address, as: :addressable
然后添加到您的Address
:
enum address_type: [:primary, :secondary]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.