class Snip < ApplicationRecord
has_many :code_blocks, inverse_of: :snip, dependent: :destroy
accepts_nested_attributes_for :code_blocks, reject_if: :all_blank, allow_destroy: true
validates :title, presence: true
validates :code_blocks, presence: true
end
class SnipsController < ApplicationController
def create
@snip = current_member.snips.new(snip_params)
@snip.save!
redirect_to @snip
end
private
def snip_params
params.require(:snip).permit(:title, :content, code_blocks_attributes: %i[id name hljs_language code _destroy])
end
end
Nested writes should be transactional: either everything is created or nothing is. Rails does this well when you keep validations coherent and avoid side effects in callbacks.