【问题标题】:How to save a belongs_to association for a polymorphic model with nested attributes?如何为具有嵌套属性的多态模型保存 belongs_to 关联?
【发布时间】: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"}}

这不起作用,因为当 ma​​in_address 的可寻址(addressable_idaddressable_type)不存在时,即使我尝试添加它,它也会拒绝并且不保存数据在Company 类中的main_address_attributes=(attributes) 方法中。

每当我尝试使用上述参数保存时,我都会收到此错误:

Main address addressable can't be blank

我该如何解决这个问题?

【问题讨论】:

  • 您是否要保存与address(通过main_address_id)相关的company,而后者又通过addressable与其他事物相关(CompanyPerson) ??
  • 不,Company 有两个独立的地址,一个是主地址,另一个是可选地址,Person 可以有一个地址,但不是主题。我需要的是将 main_address_id 保存为创建的Address id 的方法,其中可寻址指向创建的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


【解决方案1】:

如果使用belongs_to,您将有类似:companyaddress 相关(通过main_address_id),而后者又通过多态addressable 与另一个相关(CompanyPerson) .

例如,您可以更改:

has_one :address, as: :addressable

到:

has_many :address, as: :addressable

然后添加到您的Address:

enum address_type: [:primary, :secondary]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多