Last active
March 10, 2016 17:08
-
-
Save zkwentz/70b7c6b1dcc3bc7eafd1 to your computer and use it in GitHub Desktop.
Rails, JSONAPI, and strong_params, making them work
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/controllers/posts_controller.rb | |
class PostsController < ApplicationController | |
include RestifyParam | |
... | |
def post_params | |
restify_param(:post).require(:post).permit( | |
:id, | |
:title, | |
:body, | |
comments: [ | |
:id, | |
:body | |
] | |
) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/controllers/concerns/restify_param.rb | |
module RestifyParam | |
extend ActiveSupport::Concern | |
def restify_param(param_key) | |
ActionController::Parameters.new(param_key => restify_value(param_key)) | |
end | |
private | |
def restify_value(param_key, value = params) | |
if value == params | |
value = params.clone | |
end | |
if value[:data] | |
if value[:data].delete(:type) == param_key.to_s.pluralize | |
new_params = ActionController::Parameters.new | |
attributes = value[:data].has_key?(:attributes) ? value[:data][:attributes] : value[:data] | |
attributes.transform_keys!(&:underscore) | |
new_params.merge!(attributes) | |
if value[:data].has_key? :relationships | |
value[:data][:relationships].each do |k,v| | |
if k.pluralize != k | |
new_params["#{k}_id"] = v[:data][:id] #belongs_to | |
else | |
new_params[k.to_s.underscore+"_attributes"] = restify_value(k,v) #has_many | |
end | |
end | |
end | |
new_params | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment