Skip to content

Commit

Permalink
raise ArgumentError when the wrong name is passed to lr_has_nested_at…
Browse files Browse the repository at this point in the history
…tributes_for
  • Loading branch information
msimonborg committed Jul 20, 2017
1 parent 8efa4d9 commit 04d5c05
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
5 changes: 3 additions & 2 deletions example/person.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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) { {} }
Expand Down
9 changes: 9 additions & 0 deletions lib/lazy_record/collections.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
6 changes: 6 additions & 0 deletions spec/lazy_record/collections_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 04d5c05

Please sign in to comment.