Techblog

Tech Blog

Our latest geek adventures!

17 July Rails ActionWebservice :: Type casting

Posted by jaap on in Ruby on Rails

Today we started the development of a Rails API. The first thing we had to do was defining a cast from a model to a Struct, cause we didn’t want the API to send all the fields we have in some tables.
In the rails documentation I could only find that it was possible to hide fields from your models, but not how. This is how we did it. We included the defined the models as a base class ActionWebService::Struct within our Api class. Example:

Let’s say you have a model User (who doesn’t) which has as base class ActiceRecord::Base. Now we want to only show, let’s say the field email.
This is our API for now:

class SomeApi < ActionWebService::API::Base
class User < ActionWebService::Struct
member :email, :string
end
 
api_method :get_user,
:returns => [User]
 
end

Now the User model with 20 fields will only be casted through a Struct and sent through the webservice with only the field email. That’s what we wanted!

Leave a Reply