Theo Felippe
Theo Felippe

Reputation: 279

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.

Upvotes: 4

Views: 1551

Answers (3)

Antonio Carlos
Antonio Carlos

Reputation: 1

ActiveAdmin.register Project do
  controller do
    def apply_filtering(chain)
      super(chain).distinct
    end
  end

  # your code
end

Upvotes: -1

nistvan
nistvan

Reputation: 2960

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.

Upvotes: 14

Alex P
Alex P

Reputation: 6072

I think this is the same problem as this one discussed on the CarrierWave wiki. Instead of generating input fields for existing images, generate an image tag and a 'remove?' option. If you generate an input field for them, then you'll end up with duplicate results.

Upvotes: 0

Related Questions