在ActiveAdmin中编辑has_one关联-在属性为空时销毁 [英] Editing a has_one association in ActiveAdmin - destroying when attribute is blanked

查看:83
本文介绍了在ActiveAdmin中编辑has_one关联-在属性为空时销毁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,其中很小比例的对象将具有相当大的描述性文本。为了使数据库保持某种标准化,我想将此描述性文本提取到一个单独的模型中,但在ActiveAdmin中创建合理的工作流时遇到了麻烦。

I've got a model in which a very small percentage of the objects will have a rather large descriptive text. Trying to keep my database somewhat normalized, I wanted to extract this descriptive text to a separate model, but I'm having trouble creating a sensible workflow in ActiveAdmin.

我的模型如下:

class Person < ActiveRecord::Base
  has_one :long_description

  accepts_nested_attributes_for :long_description, reject_if: proc { |attrs| attrs['text'].blank? }
end

class LongDescription < ActiveRecord::Base
  attr_accessible :text, :person_id
  belongs_to :person

  validates :text, presence: true
end

当前,我已经创建了一个用于编辑Person模型的表单,看起来有点像这样:

Currently I've created a form for editing the Person model, looking somewhat like this:

  form do |f|
    ...
    f.inputs :for => [
                      :long_description,
                      f.object.long_description || LongDescription.new
                     ] do |ld_f|
      ld_f.input :text
    end

    f.actions
  end

这可用于添加/编辑LongDescription对象,并且如果没有输入任何文本,它会自动验证/创建LongDescription对象。

This works for adding/editing the LongDescription object, and it avdois validating/creating the LongDescription object if no text is entered.

我想实现的是还能够删除LongDescription对象,例如,如果 text 属性再次设置为空字符串/nil。

What I'd like to achieve is to also be able to remove the LongDescription object, for example if the text attribute is ever set to an empty string/nil again.

具有比我更好的Rails或ActiveAdmin技能的人都知道如何实现此目标?

Anyone with better Rails or ActiveAdmin skills than me know how to achieve this?

推荐答案

这似乎是一个非常不寻常的体系结构决定,但实现起来却很简单:

That seems like an awfully unusual architecture decision, but the implementation is pretty simple:

class LongDescription < ActiveRecord::Base

  validates_presence_of :text, on: :create

  after_save do
    destroy if text.blank?
  end
end

这篇关于在ActiveAdmin中编辑has_one关联-在属性为空时销毁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆