Jabba the Hutt Jabba the Hutt - 2 months ago 10
Ruby Question

Destroy an object in model file if its missing a condition

How can i destroy this object if its category_attributes(:title) is empty?

def categories_attributes=(categories_attributes)
categories_attributes.values.each do |category_attribute|
category = Category.find_or_create_by(category_attribute)
categories << category
end
end

Answer

Try this:

def categories_attributes=(categories_attributes)
  categories_attributes.values.each do |category_attribute|
    category = Category.find_or_create_by(category_attribute)
    if category.title?
      categories << category
    elsif category.persisted?
      category.destroy
    end
  end
end
Comments