-
Notifications
You must be signed in to change notification settings - Fork 534
Create through association (default params)
David Henner edited this page Dec 10, 2015
·
1 revision
Given:
- You have a current_user
- You want to do something like
current_user.comments.create(params)
in the controller create method.
Instead of over-riding the CommentsController
you just need to change the CommentResource
like this:
class CommentResource < JSONAPI::Resource
def self.create(context)
CommentResource.new(context[:current_user].comments.new, nil)
end
end
It is considered good practice to ensure the user can not be passed via your API so you should also update your creatable_fields
method like this:
class CommentResource < JSONAPI::Resource
def self.create(context)
CommentResource.new(context[:current_user].comments.new, nil)
end
def creatable_fields(_context = nil)
super - [:user]
end
end
Also if to wanted to add a default parameter you could do something like:
class CommentResource < JSONAPI::Resource
def self.create(context)
CommentResource.new(context[:current_user].comments.new(status: 'active'), nil)
end
def creatable_fields(_context = nil)
super - [:user, :status]
end
end