ActiveAdmin Form not saving nested object

╄→尐↘猪︶ㄣ 提交于 2020-01-14 12:38:19

问题


Using ActiveAdmin with Rails 4, I have two models, Document and Attachment with a one-to-many relationship between them.

# models/document.rb
class Document < ActiveRecord::Base
    has_many :attachments

    accepts_nested_attributes_for :attachments
end

# models/attachment.rb
class Attachment < ActiveRecord::Base
    belongs_to :document
end

I registered the models and included permit_params for all the fields in each. Now I used has_many in the form view in the below code. This shows an option to add Attachments and it work just fine.

 # admin/document.rb
 ActiveAdmin.register Document do
    permit_params :title, :description, :date, :category_id

    show do |doc|
        attributes_table do 
            row :title
            row :description
            row :attachments do 
                doc.attachments.map(&:document_path).join("<br />").html_safe
            end
        end
    end

    form do |f|
        f.inputs "Details" do
            f.input :title
            f.input :description
            f.input :category
            f.has_many :attachments, :allow_destroy => true do |cf|
                cf.input :document_path # which is a field in the Attachment model
            end
        end
        f.actions
    end
end

However, when I submit the form, the document object is saved but no attachment objects are saved with it. As much as I understand it should create as many attachments I added in the form and pass in their document_id attribute the created document ID. Unfortunately this is not happening leaving the Attachment row "EMPTY" in the show view. Am I missing something?

Thanks in advance.


回答1:


You forgot to permit attachments_attributes. In order to use accepts_nested_attribute_for with Strong Parameters, you will need to specify which nested attributes should be whitelisted.

More info http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html



来源:https://stackoverflow.com/questions/20648081/activeadmin-form-not-saving-nested-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!