Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions lib/jsonapi/resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,8 @@ def attribute(attr, options = {})
ActiveSupport::Deprecation.warn('Id without format is no longer supported. Please remove ids from attributes, or specify a format.')
end

check_duplicate_attribute_name(attr) if options[:format].nil?

@_attributes ||= {}
@_attributes[attr] = options
define_method attr do
Expand Down Expand Up @@ -879,6 +881,8 @@ def _add_relationship(klass, *attrs)

check_reserved_relationship_name(relationship_name)

check_duplicate_relationship_name(relationship_name)

# Initialize from an ActiveRecord model's properties
if _model_class && _model_class.ancestors.collect{|ancestor| ancestor.name}.include?('ActiveRecord::Base')
model_association = _model_class.reflect_on_association(relationship_name)
Expand Down Expand Up @@ -1009,6 +1013,18 @@ def check_reserved_relationship_name(name)
warn "[NAME COLLISION] `#{name}` is a reserved relationship name in #{_resource_name_from_type(_type)}."
end
end

def check_duplicate_relationship_name(name)
if _relationships.include?(name.to_sym)
warn "[DUPLICATE RELATIONSHIP] `#{name}` has already been defined in #{_resource_name_from_type(_type)}."
end
end

def check_duplicate_attribute_name(name)
if _attributes.include?(name.to_sym)
warn "[DUPLICATE ATTRIBUTE] `#{name}` has already been defined in #{_resource_name_from_type(_type)}."
end
end
end
end
end
2 changes: 0 additions & 2 deletions test/fixtures/active_record.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1501,8 +1501,6 @@ class LineItemResource < V6::LineItemResource; end

class CustomerResource < V6::CustomerResource
model_name 'Api::V7::Customer'
attribute :name
has_many :purchase_orders
end

class ClientResource < JSONAPI::Resource
Expand Down
16 changes: 16 additions & 0 deletions test/unit/resource/resource_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,22 @@ def test_class_relationships
assert_equal(relationships.size, 2)
end

def test_duplicate_relationship_name
assert_output nil, "[DUPLICATE RELATIONSHIP] `mother` has already been defined in CatResource.\n" do
CatResource.instance_eval do
has_one :mother, class_name: 'Cat'
end
end
end

def test_duplicate_attribute_name
assert_output nil, "[DUPLICATE ATTRIBUTE] `name` has already been defined in CatResource.\n" do
CatResource.instance_eval do
attribute :name
end
end
end

def test_find_with_customized_base_records
author = Person.find(1)
posts = ArticleResource.find([], context: author).map(&:_model)
Expand Down