Last active
October 12, 2020 06:41
-
-
Save jcrisp/a6c9265dfcc044bd346cb29f813feac1 to your computer and use it in GitHub Desktop.
ActiveModel nested attributes with validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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