Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Has_one relation doesn't check for existence #70

Closed
7h3kk1d opened this issue Jan 28, 2015 · 5 comments
Closed

Has_one relation doesn't check for existence #70

7h3kk1d opened this issue Jan 28, 2015 · 5 comments

Comments

@7h3kk1d
Copy link

7h3kk1d commented Jan 28, 2015

I'm not sure if I'm doing something wrong but I have a has_one relationship in one of my resources and if I create an instance using the create route and put in a links parameter. It doesn't check if the associated record exists before retrieving it.

@7h3kk1d 7h3kk1d closed this as completed Jan 28, 2015
@lgebhardt
Copy link
Member

I was just starting to look at this. What was the resolution?

@7h3kk1d
Copy link
Author

7h3kk1d commented Jan 28, 2015

I reworked something on my end so it didn't matter anymore. I didn't want to create more work if no one else was complaining.

@lgebhardt
Copy link
Member

Ok, thanks. I'll still take a look at it then.

@lgebhardt
Copy link
Member

Were you seeing the normal Rails behavior of not validating the existence of a related object? If so, there are a few ways you can fix that. The first is using a validation gem such as https://github.com/perfectline/validates_existence, which I have not tested. Another way would be to put foreign key constraints on the database and handle the error when the resource is saved. And finally you could override the verify_key method on your resource (or base_resource). For example:

def verify_key(key, context = nil)
  #try to load a resource to make sure it exists. Will raise a JSONAPI::Exceptions::RecordNotFound if the resource is not found
  find_by_key(key, context: context)
  return key
end

I personally like overriding the verify_key method, however if you use your models outside of jsonapi-resources one of the other approaches might be better. I'm also a firm believer in foreign keys as an additional safety measure.

One final note, using the verify_key method can also provide a way to check if the current user has permission to see the related record since the context can be taken into account during the find_by_key method.

@7h3kk1d
Copy link
Author

7h3kk1d commented Jan 29, 2015

Okay. Thanks very much! I added the database constraint.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants