【问题标题】:Rails 4 Accept nested attributes with has_one associationRails 4 接受带有 has_one 关联的嵌套属性
【发布时间】:2021-01-28 12:23:12
【问题描述】:

我有一个关于 Rails 嵌套属性的问题。 我正在使用 Rails 4 并且有这个模型:

model Location
 has_one parking_photo
 has_many cod_photos
 accepts_nested_attributes_for :parking_photo
 accepts_nested_attributes_for :cod_photos
end

当我使用例如: Location.find(100).update(cod_photo_ids: [1,2,3]) 有效。

但是Location.find(100).update(parking_photo_id: 1) 不起作用。

我不知道嵌套属性 has_one 和 has_many 有什么区别。

或者当我已经有子对象并且想要将父对象链接到子对象并且不想使用子更新时,我们是否有任何解决方案。

谢谢。

【问题讨论】:

  • 你可以试试Location.find(100).update( parking_photo: ParkingPhoto.find(1) ),它应该改变子对象中的location_id

标签: ruby-on-rails nested-attributes accepts-nested-attributes


【解决方案1】:

问题与嵌套属性无关。事实上,在这些示例中,您甚至根本没有使用嵌套属性。

在这个例子中:

Location.find(100).update(cod_photo_ids: [1,2,3])

即使您将 accepts_nested_attributes_for :cod_photos 注释掉,因为 cod_photo_ids= 设置器是由 has_many :cod_photos 创建的,这仍然有效。

在另一个示例中,您使用的是has_one,而您应该使用belongs_to,或者只是对如何建模关联感到困惑。 has_one 将外键放在 parking_photos 表中。

如果您想将parking_photo_id 放在locations 表上,您可以使用belongs_to

class Location < ActiveRecord::Base
  belongs_to :parking_photo
  # ...
end

class ParkingPhoto < ActiveRecord::Base
  has_one :location # references  locations.parking_photo_id
end 

当然,您还需要迁移才能实际添加locations.parking_photo_id 列。我真的建议您暂时忘记嵌套属性,而只需弄清楚基础知识of how assocations work in Rails

如果你真的想建立反比关系并将location_id 放在parking_photos 上,你可以这样设置:

class Location < ActiveRecord::Base
  has_one :parking_photo
  # ...
end

class ParkingPhoto < ActiveRecord::Base
  belongs_to :location
  validates_uniqueness_of :location_id
end 

您可以通过以下方式重新分配照片:

Location.find(100).parking_photo.update(location_id: 1)

【讨论】:

    猜你喜欢
    • 2014-01-08
    • 2012-05-09
    • 2014-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多