w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
rails creating default child when parent doesn't have children and not showing it when parent has children

after_create should work just fine, assuming you associated any children before saving the parent:

class ParentModel < ActiveRecord::Base
  has_many :child_models
  after_create :ensure_child_exists

  def ensure_child_exists
    child_models.create(default: true) unless child_models.exists?
  end
end

If you then need to remove this child if new ones are added at some later point, you'll need to have a 'default' flag on the child to identify for removal, then add a callback to trigger the default child removal.

class ChildModel < ActiveRecord::Base
  attr_accessible :default
  belongs_to :parent
  after_create :remove_default_if_unneeded

  scope :default, -> { where(default: true) }

  def remove_default_if_unneeded
    parent.child_models.default.destroy_all unless self.default?
  end
end




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.