2014-06-15 104 views
4

我的型號如下:導軌 - activeadmin,在更新的「父」記錄重複的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文件:

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 

的問題是,當我簡單地編輯項目並點擊更新項目,它只是複製當時關係中存在的所有記錄。例如。如果我在1個項目下有2個圖像,在改變後說出項目標題,我將以4個圖像結束。

希望很清楚問題所在。如果有人能給我一點幫助,我會很感激。

非常感謝。

回答

13

你必須使圖像的ID:project_images_attributes: [:id, :image, :cover]

如果不允許ID,這將是在動作空,軌道認爲這是一個新的記錄並保存。

+0

我還沒有時間來測試這個呢。但它總是有意義的。所以你得到賞金:) –

+0

謝謝。 :D我有同樣的問題,這是解決方案。 – nistvan

0

我認爲這與在CarrierWave wiki上討論的this one相同。不是爲現有圖像生成輸入字段,而是生成圖像標記和「刪除?」。選項。如果你爲它們生成一個輸入字段,那麼你最終會得到重複的結果。

+0

我不確定,因爲它不替代文件。它複製當前項目實例的project_images的記錄數量。 –

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

    # your code 
end 
+1

當他們也包含解釋時,答案更有幫助。 –