Skip to content

Instantly share code, notes, and snippets.

@jcrisp
Last active October 12, 2020 06:41
Show Gist options
  • Save jcrisp/a6c9265dfcc044bd346cb29f813feac1 to your computer and use it in GitHub Desktop.
Save jcrisp/a6c9265dfcc044bd346cb29f813feac1 to your computer and use it in GitHub Desktop.
ActiveModel nested attributes with validation
class Order
include ActiveModel::Model
attr_accessor :order_lines, :name
def initialize(*params)
self.order_lines = []
super
end
def order_lines_attributes=(attributes)
attributes.each do |i, order_lines_params|
@order_lines.push(OrderLine.new(order_lines_params))
end
end
def valid?
parent_valid = super
children_valid = order_lines.map(&:valid?).all?
order_lines.each do |ol|
ol.errors.each do |attribute, error|
errors.add(:order_lines_attributes, error)
end
end
errors[:order_lines_attributes].uniq!
parent_valid && children_valid
end
end
class OrderLine
include ActiveModel::Model
attr_accessor :line_number, :item_number # etc
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment