4

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 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

Yes I figured it out. ruby controller do def permitted_params params.permit! end end did the job. Cheers!
Omar F, can you write more detail answer, meet same problem.
For anyone who comes across this, you SHOULD NEVER override strong perameters like Omar F said he did above. It will make your app a security nightmare immediately.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.