diff --git a/example/person.rb b/example/person.rb index 86ff133..b0a6a4e 100644 --- a/example/person.rb +++ b/example/person.rb @@ -3,9 +3,10 @@ # Example class class Person < LazyRecord::Base attr_accessor :name, :age, :haircut - lr_has_many :dogs, :cats + lr_has_many :dogs + lr_has_many :kitties, class_name: 'Cat' lr_has_one :friend - lr_accepts_nested_attributes_for :dogs, :cats + lr_accepts_nested_attributes_for :dogs, :kitties lr_scope :new_with_dog, lambda { |opts = {}| dog = opts.fetch(:dog) { {} } diff --git a/lib/lazy_record/collections.rb b/lib/lazy_record/collections.rb index 4c56fe1..dcb3226 100644 --- a/lib/lazy_record/collections.rb +++ b/lib/lazy_record/collections.rb @@ -92,9 +92,18 @@ def lr_accepts_nested_attributes_for(*collections) mod.module_eval do collections.each do |collection| options = _collections[collection] + _no_collection_error(collection) unless options define_collection_attributes_setter(collection, options) end end end + + def _no_collection_error(collection) + klass = collection.to_s.classify + klass = _collections.find { |_col, opt| opt[:class_name] == klass }.first + suggestion = klass ? ". Did you mean #{klass}?" : '' + msg = "#{self} doesn't have a collection of #{collection}#{suggestion}" + raise ArgumentError, msg, caller + end end end diff --git a/spec/lazy_record/collections_spec.rb b/spec/lazy_record/collections_spec.rb index 5b1c21f..6575474 100644 --- a/spec/lazy_record/collections_spec.rb +++ b/spec/lazy_record/collections_spec.rb @@ -88,5 +88,11 @@ expect(parent.children.map(&:age)).to eq [11, 12] expect(parent.brothers.map(&:name)).to eq %w[Sue Bob] end + + it 'does not allow accepting nested attributes unless it has the collection' do + block = -> { Parent.class_eval { lr_accepts_nested_attributes_for :siblings } } + + expect(&block).to raise_error(ArgumentError, "Parent::Collections doesn't have a collection of siblings. Did you mean brothers?") + end end end