保存前ActiveAdmin表单验证

时间:2015-02-26 16:52:33

标签: ruby-on-rails-4 activeadmin

我在status_history编辑中包含了一个模型member的表单字段。我想这样做,如果status_history的字段为空,那么它将无法保存。目前,当我保存status_history编辑时,它会将空白项目保存到members

我的member表格看起来像这样

form(:html => { :multipart => true }) do |f|
    f.semantic_errors *f.object.errors.keys
    columns do
      column do
        ...
      end
      column do
        f.inputs "Status" do
          f.semantic_fields_for :status_histories, StatusHistory.new do |sh|
            sh.inputs :class => "" do
              sh.input :status, as: :select, collection: {Active: "active", Inactive: "inactive", Separated: "separated"}
              sh.input :date, :as => :datepicker
              sh.input :reason
            end
          end
          table_for member.status_histories do
            column "status" do |status_histories|
              status_histories.status
            end
            column "date" do |status_histories|
              status_histories.date
            end
            column "reason" do |status_histories|
              status_histories.reason
            end
          end
        end

...
      end
    end
    f.actions
  end

模型/ status_histories

class StatusHistory < ActiveRecord::Base
  belongs_to :member

  STATUS_TYPES = [ "active", "inactive", "separated" ]
  validates :status, inclusion: STATUS_TYPES
  validates :date, :presence => true
  validates :reason, :presence => true
end

即使添加一个可以切换semantic_fields_for的按钮也可以正常工作,但是目前如果我将它们留空,我会收到validates个错误。

如何覆盖save方法以检查状态和日期是否存在,如果存在,则保存status_history,如果不存在,则不保存status_history但保存{{1}的其余部分字段?

1 个答案:

答案 0 :(得分:1)