Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - activeadmin, duplicating has_many records upon updating "parent" record

My models are as follows:

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

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

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.

Thanks a lot in advance.

like image 737
Theo Felippe Avatar asked Dec 14 '22 22:12

Theo Felippe


1 Answers

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

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.

like image 101
nistvan Avatar answered Feb 12 '23 12:02

nistvan