Ruby on rails Rails 4接受嵌套属性,并具有一个关联
我有一个关于Rails嵌套属性的问题。 我使用的是Rails 4,有以下型号:Ruby on rails Rails 4接受嵌套属性,并具有一个关联,ruby-on-rails,nested-attributes,accepts-nested-attributes,Ruby On Rails,Nested Attributes,Accepts Nested Attributes,我有一个关于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\u photo\u id:[1,2,
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\u photo\u id:[1,2,3])
它可以工作
但是Location.find(100).update(停车照片\u id:1)
不起作用
我不知道嵌套属性有一个和有多个有什么区别
或者,当我已经有了子对象,并且想要将父对象链接到子对象,并且不想使用子对象更新时,我们有什么解决方案吗
谢谢。问题与嵌套属性无关。事实上,在这些示例中,您甚至没有使用嵌套属性 在本例中:
Location.find(100).update(cod_photo_ids: [1,2,3])
即使您注释掉接受:cod\u照片的\u嵌套的\u属性
,这也会起作用,因为cod\u照片ID=
setter是由创建的,它有许多:cod\u照片
在另一个示例中,您正在使用的有一个,您应该使用的属于,或者只是对您应该如何建模关联感到困惑<代码>有一个
将外键放置在停车照片
表上
如果您想将停车照片\u id
放在位置
表上,您可以使用归属
:
class Location < ActiveRecord::Base
belongs_to :parking_photo
# ...
end
class ParkingPhoto < ActiveRecord::Base
has_one :location # references locations.parking_photo_id
end
您可以通过以下方式重新分配照片:
Location.find(100).parking_photo.update(location_id: 1)
您可以尝试Location.find(100).update(parking\u photo:parking photo.find(1))
以更改子对象中的Location\u id
。
Location.find(100).parking_photo.update(location_id: 1)