Editing a has_one association in ActiveAdmin - destroying when attribute is blanked

℡╲_俬逩灬. 提交于 2019-12-13 05:13:05

问题


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.

My models look like this:

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

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

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

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.

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


回答1:


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


来源:https://stackoverflow.com/questions/20742041/editing-a-has-one-association-in-activeadmin-destroying-when-attribute-is-blan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!