activeadmin中的嵌套表单不保存更新

时间:2014-01-28 15:37:48

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

我在ActiveAdmin中为这些模型设置了一个嵌套表单(a:class_section has_many:class_dates):

class ClassDate < ActiveRecord::Base
  belongs_to :class_section
  validates :start_time, :presence => true
  validates :end_time, :presence => true

end

class ClassSection < ActiveRecord::Base
  belongs_to :class_course
  has_many :class_dates
  belongs_to :location

  accepts_nested_attributes_for :class_dates
end

当我查看表单时,一切似乎都在正确的位置。但是,当我更新class_date时,它不会保存。

ActiveAdmin.register ClassSection do

  permit_params :max_students, :min_students, :info, :class_course_id, :location_id

  form do |f|
    f.inputs "Details" do
      f.input :class_course, member_label: :id_num
      f.input :min_students, label: "Minunum Students"
      f.input :max_students, label: "Maxiumum Students"
      f.input :location
    end
    f.inputs do
      f.input :info, label: "Additional Information"
    end
    f.inputs "Dates" do
      f.has_many :class_dates, heading: false do |cd|
        cd.input :start_time, :as => :datetime_picker
        cd.input :end_time, :as => :datetime_picker
      end
    end
    f.actions
  end

  index do
    column :class_course
    column :location
    default_actions
  end

  filter :class_course
  filter :location

  show do |cs|
    attributes_table do
      row :class_course do
        cs.class_course.id_num + " - " + cs.class_course.name
      end
      row :location
      row :min_students, label: "Minunum Students"
      row :max_students, label: "Maxiumum Students"
      row :info, label: "Additional Information"
    end

    panel "Dates" do
      attributes_table_for class_section.class_dates do
        rows :start_time, :end_time
      end
    end
    active_admin_comments
  end 

end

以下是ClassDates的ActiveAdmin文件:

ActiveAdmin.register ClassDate, as: "Dates" do

  permit_params :start_time, :end_time, :class_section_id

  belongs_to :class_section

end

你能看出为什么没有妥善保存的原因吗?

更新:我在AA中添加了以下代码,现在似乎可以正常运行:

controller do
  def permitted_params
    params.permit!
  end
end

如果有更好的解决方案,请告诉我。感谢。

更新2:然而,有一个挥之不去的问题。我无法使用此表单删除ClassDates。

1 个答案:

答案 0 :(得分:34)

您需要允许嵌套参数,但从不使用params.permit!。这是非常不安全的。试试这个:

ActiveAdmin.register ClassSection do
  permit_params :max_students, :min_students, :info, :class_course_id, :location_id, 
                class_dates_attributes: [ :id, :start_time, :end_time, :_destroy ]

  form do |f|
    # ...
    f.inputs "Dates" do
      f.has_many :class_dates, heading: false, allow_destroy: true do |cd|
        cd.input :start_time, :as => :datetime_picker
        cd.input :end_time, :as => :datetime_picker
      end
    end
    f.actions
  end

  # ...
end

permitted_params管理面板的配置(和ClassDate)与ClassSection管理面板中的许可参数无关。在应用程序中将它们视为单独的控制器。

allow_destroy: true调用中添加has_many选项会在表单中添加一个复选框,以便您在表单提交时删除课时。