JSONAPI-Resources / JSONAPI-Resources/jsonapi-resources
Resource interacts with HasOne and HasMany differently
Nobody has claimed this yet.
- Dominant language
- Ruby
- Stars
- 2.3k
- Forks
- 546
- PR merge metrics
- No merged PRs in 30d
Description
I have a model (User) that I want to expose on an API to a certain class of users. Those users will always have a given permission and expiration, so I want to set those on the server, rather than expose uneditable fields to the client.
class UserResource < JSONAPI::Resource
has_many :permissions
has_one :expiration, foreign_key_on: :related
before_create :add_defaults
def add_defaults
self.permissions << Permission.find_by(title: 'Admin')
self.model.expiration = Expiration.new(date: Date.new(2015,12,30))
end
I think it's odd that I need to call the underlying model in order to interact with has_one objects, and I suspect this is the case for created objects, but I haven't gotten that far yet. Ideally, I could call self.expiration= and I would get behavior similar to self.permissions<<.
Am I just using JSONAPI::Resource incorrectly, or is this something worth pursuing?
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the UserResource relationship declarations and its before_create callback, comparing the has_many permissions interaction with the has_one expiration interaction. Determine the expected resource-level assignment and creation behavior, then verify that has_one handling matches the requested has_many-like behavior with focused tests.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rails, ruby
- Domain
- api, backend
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100