例如我有这些模型:
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_id
和addressable_type
)时,这不起作用,因为它拒绝并且不会保存数据现在,即使我试图在main_address_attributes=(attributes)
类的Company
方法中添加它。
每当我尝试使用上述参数保存时,我会收到此错误:
Main address addressable can't be blank
如何解决此问题?
答案 0 :(得分:0)
如果使用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]