使用自定义控制器操作在activeadmin中进行验证

时间:2019-01-09 17:27:42

标签: ruby-on-rails validation controller activeadmin

在我们的网络应用程序中,组成通过名为 contributions 的表具有许多作者。我们要检查管理员是否没有意外删除activeadmin中一个组成的所有作者(至少应保留一名作者)。如果发生这种情况,更新将失败并显示一条错误消息,并再次呈现合成的编辑视图。

使用调用模型验证

validates_presence_of :authors, on: :update

在这里不合适,因为在调用activeadmin控制器的更新功能上的success.html时添加了新的贡献(因此是作者),以防止以前的一些错误为作者创建了重复条目。 / p>

模型是:

class Composition < ApplicationRecord
  has_many :contributions
  has_many :authors, through: :contributions
end
----
class Contribution < ApplicationRecord
  belongs_to :composition
  belongs_to :author
end
----
class Author < ApplicationRecord
  has_many :author_roles, dependent: :delete_all
  has_many :contributions
  has_many :compositions, through: :contributions
end

我们在admin中的代码具有一些后台逻辑来处理之前描述的内容:

ActiveAdmin.register admin_resource_name = Composition do
  ...
  controller do
    def update
      author = []
      contribution_delete = []
      params[:composition][:authors_attributes].each do |number, artist|
        if artist[:id].present?
          if artist[:_destroy] == "1"
            cont_id = Contribution.where(author_id: artist[:id],composition_id: params[:id]).first.id
            contribution_delete << cont_id
          end  
        else
          names = artist[:full_name_str].strip.split(/ (?=\S+$)/)
          first_name = names.size == 1 ? '' : names.first
          exist_author = Author.where(first_name: first_name, last_name: names.last, author_type: artist[:author_type]).first
          author << exist_author.id if exist_author.present?
        end
      end if params[:composition][:authors_attributes] != nil
      params[:composition].delete :authors_attributes
      update! do |success, failure|
        success.html do
          if author.present?
            author.each do |id|
              Contribution.create(author_id: id, composition_id: params[:id])
            end
          end  

          if contribution_delete.present?
            contribution_delete.each do |id|
              Contribution.find(id).destroy
            end
          end
          ...
          redirect_to admin_composition_path(@composition.id)
        end
        failure.html do
          render :edit
        end
      end
    end
  end
  ...
end

如果要删除的作者人数等于现有人数,您是否知道如何控制authors_attributes并发出“至少必须有一位作者”这样的简短消息?作者?

我认为也许可以在update!调用之前进行处理,以便以某种方式将成功转化为失败,但是我不知道如何。

0 个答案:

没有答案