是否可以通过使用表单的关联来附加/取消附加一个has_one ?



我的模特是这样的

class Photo

   has_one :photo_gallery
   has_one :gallery, through: :photo_gallery
end
class PhotoGallery
   belongs_to :photo
   belongs_to :gallery
end
class Gallery
   has_many :photo_galleries
   has_many :photos, through: :photo_galleries
end

对于这个问题,从Gallery.only_gallery中可以得到一个单独的Gallery

我想Photo的形式包含一个复选框。

如果在提交表单时选中复选框,则照片通过PhotoGallery模型与Gallery.only_gallery相关联。如果未检查,则销毁此关联。

这可能吗?

我知道如何设置强参数来接受任何必要的东西。我不明白的是如何创建一个表单,可以做到这一点。

你真的不应该通过表单修改关联:它们要么存在,要么不存在。

在您的示例中,如果您不选中复选框,则不会在两个模型的连接表中创建任何行,因此您应该不会有问题。

我建议在您的表单中添加这样的内容photo:

<%= f.label :gallery_ids %> <br>
<%= collection_select(:photo, :gallery_ids, Gallery.all, :id, :name) %>

和add

dependent: :nullify

到你的模型关联

相关内容

最新更新