【问题标题】:ActiveAdmin Form not saving nested objectActiveAdmin 表单不保存嵌套对象
【发布时间】:2013-12-18 01:28:36
【问题描述】:

在 Rails 4 中使用 ActiveAdmin,我有两个模型,Document 和 Attachment,它们之间存在一对多关系。

# 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

我注册了模型并为每个模型的所有字段添加了permit_params。 现在我在下面代码的表单视图中使用了has_many。这显示了一个添加附件的选项,它工作得很好。

 # 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

但是,当我提交表单时,文档对象被保存,但没有附件对象被保存。据我所知,它应该创建我在表单中添加的尽可能多的附件,并在其 document_id 属性中传递创建的文档 ID。不幸的是,在显示视图中留下附件行“EMPTY”并没有发生这种情况。我错过了什么吗?

提前致谢。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 activeadmin formtastic


    【解决方案1】:

    您忘记允许附件属性。 为了使用带有强参数的accepts_nested_attribute_for,您需要指定哪些嵌套属性应该被列入白名单。

    更多信息http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html

    【讨论】:

    • 是的,我想通了。 ruby controller do def permitted_params params.permit! end end 完成了这项工作。干杯!
    • Omar F,你能写更详细的答案吗,遇到同样的问题。
    • 对于遇到此问题的任何人,您都不应像 Omar F 所说的那样覆盖强参数。它会让您的应用立即成为安全噩梦。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-26
    相关资源
    最近更新 更多