【发布时间】:2014-08-31 16:02:36
【问题描述】:
例如我有这些模型:
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)不存在时,即使我尝试添加它,它也会拒绝并且不保存数据在Company 类中的main_address_attributes=(attributes) 方法中。
每当我尝试使用上述参数保存时,我都会收到此错误:
Main address addressable can't be blank
我该如何解决这个问题?
【问题讨论】:
-
您是否要保存与
address(通过main_address_id)相关的company,而后者又通过addressable与其他事物相关(Company或Person) ?? -
不,
Company有两个独立的地址,一个是主地址,另一个是可选地址,Person可以有一个地址,但不是主题。我需要的是将 main_address_id 保存为创建的Addressid 的方法,其中可寻址指向创建的Company。我希望这会有所帮助。 -
在这种情况下,您应该使用相同的
polymorphic关系(否则您会对我上面写的内容有所了解) -
这不是您的问题的答案,但看起来您应该将
has_one :address, as: :addressable更改为has_many :address, as: :addressable,然后将enum type: [:primary, :secondary]添加到您的Address -
感谢您的建议。我会寻找更多的选择,如果我找不到任何我会接受你的答案。所以,把你的建议放在答案中。另外,请注意您不能将
enum用作type,因为列是为单表继承保留的。它可以是 address_type 或其他东西。还是谢谢你。 :)
标签: ruby-on-rails activerecord ruby-on-rails-4 polymorphic-associations