Skip to content

Commit 525ee5a

Browse files
committed
Merge pull request #293 from cerebris/primary_key_rework
Adds feature that the resource interrogates the model for the primary key.
2 parents 8e4702c + 5f75375 commit 525ee5a

3 files changed

Lines changed: 8 additions & 6 deletions

File tree

README.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -178,10 +178,10 @@ updating the attribute. See the [Value Formatters](#value-formatters) section fo
178178

179179
#### Primary Key
180180

181-
Resources are always represented using a key of `id`. If the underlying model does not use `id` as the primary key you
182-
can use the `primary_key` method to tell the resource which field on the model to use as the primary key. Note: this
183-
doesn't have to be the actual primary key of the model. For example you may wish to use integers internally and a
184-
different scheme publicly.
181+
Resources are always represented using a key of `id`. The resource will interrogate the model to find the primary key.
182+
If the underlying model does not use `id` as the primary key _and_ does not support the `primary_key` method you
183+
must use the `primary_key` method to tell the resource which field on the model to use as the primary key. **Note:**
184+
this _must_ be the actual primary key of the model.
185185

186186
By default only integer values are allowed for primary key. To change this behavior you can override
187187
`verify_key` class method:

lib/jsonapi/resource.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -577,7 +577,7 @@ def _model_name
577577
end
578578

579579
def _primary_key
580-
@_primary_key ||= :id
580+
@_primary_key ||= _model_class.respond_to?(:primary_key) ? _model_class.primary_key : :id
581581
end
582582

583583
def _as_parent_key

test/fixtures/active_record.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -673,6 +673,9 @@ class PostResource < JSONAPI::Resource
673673
has_many :tags, acts_as_set: true
674674
has_many :comments, acts_as_set: false
675675

676+
# Not needed - just for testing
677+
primary_key :id
678+
676679
before_save do
677680
msg = "Before save"
678681
end
@@ -763,7 +766,6 @@ class HairCutResource < JSONAPI::Resource
763766
end
764767

765768
class IsoCurrencyResource < JSONAPI::Resource
766-
primary_key :code
767769
attributes :name, :country_name, :minor_unit
768770

769771
filter :country_name

0 commit comments

Comments
 (0)