问题
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