I'm building an API using ActiveModel::Serializers. What is the best way to sideload data conditionally using params?
So I can make requests like GET /api/customers
:
"customers": {
"first_name": "Bill",
"last_name": "Gates"
}
And GET /api/customers?embed=address,note
"customers": {
"first_name": "Bill",
"last_name": "Gates"
},
"address: {
"street": "abc"
},
"note": {
"body": "Banned"
}
Something like that depending on the params. I know ActiveModel::Serializers has the include_[ASSOCIATION]?
syntax but how can I use it efficiently from my controllers?
This is my current solution, but it's not neat:
customer_serializer.rb:
def include_address?
!options[:embed].nil? && options[:embed].include?(:address)
end
application_controller.rb:
def embed_resources(resources = [])
params[:embed].split(',').map { |x| resources << x.to_sym } if params[:embed]
resources
end
customers_controller.rb:
def show
respond_with @customer, embed: embed_resources
end
Must be an easier way?