Rails-activeadmin,在更新“ parent”信息时复制has_many记录记录 [英] Rails - activeadmin, duplicating has_many records upon updating "parent" record

查看:67
本文介绍了Rails-activeadmin,在更新“ parent”信息时复制has_many记录记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型如下:

class Project < ActiveRecord::Base
  has_many :project_images
  accepts_nested_attributes_for :project_images
end

class ProjectImage < ActiveRecord::Base
  belongs_to :project
  mount_uploader :image, ImageUploader
end

这是activeadmin文件:

Here's the activeadmin file:

ActiveAdmin.register Project do
  remove_filter :projects_sectors
  permit_params :title, :info, :case_study, project_images_attributes: [:image, :cover]

  index do
    column :title
    actions
  end

  form :html => { :enctype => "multipart/form-data" } do |f|
    f.inputs "Project" do
    f.input :title
    f.input :info
    f.input :case_study, :as => :file
  end

  f.inputs "Images" do
    f.has_many :project_images, :allow_destroy => true, :heading => false, :new_record => true do |img_f|
      img_f.input :image, :as => :file , :hint => f.template.image_tag(img_f.object.image)
      img_f.input :cover
    end
  end
  f.actions
end


end

问题是当我简单地编辑一个项目并单击更新项目时,它只是复制当时存在的所有关系记录。例如。如果我在一个项目下有2张图片,则在更改项目标题后,我将得到4张图片。

The problem is that when i simply edit a project and click on update project, it simply duplicates all the records that exist for relationship at that point. Eg. if i have 2 images under 1 project, after changing say, the project title, i will end up with 4 images.

希望很明显,问题出在哪里。如果有人可以给我一点帮助,将不胜感激。

Hope it's clear what the issue is. Would appreciate greatly if anybody could give me a litle help.

请多多关照。

推荐答案

您必须允许图像的ID: project_images_attributes:[:id,:image,:cover]

You have to permit the id of the images: project_images_attributes: [:id, :image, :cover]

如果您不允许使用该ID,则该操作将为null,Rails认为这是新记录并保存。

If you don't permit the id, it will be null in the action, and rails thinks it's a new record and save it.

这篇关于Rails-activeadmin,在更新“ parent”信息时复制has_many记录记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆