You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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