Sunday, June 9, 2013

AngularJS, Rails, and resources (aka models)

I'm building a web application with Angular JS and Rails.  Here's one little challenge I ran into and my solution, both for my memory and anyone else that might run into the same (simple) problem.

Problem:  When loading Angular Resources from a Rails server, the Angular JS model ends up attributes you may want to just leave on the server.  E.g. created_at and updated_at.  If they are in the Angular JS model, when your code updates the model, Rails throws some sort of attribute permission error (either a mass assignment error, Forbidden Attributes error, ...).

I wasn't using anything to serialize and render the JSON.  (That turns out to be the catch).

Solution:  I ended up using active_model_serializers to build the JSON and omitted those items.  Most examples out there just assume you're already doing this.

Discussion:

Both InheritedResources, restful_json, and angularjs-rails-resource out of the box don't do any filtering on the attributes.  They kind of assume you're already using something to build the JSON that you want returned.  If you aren't (I wasn't), you get create_at and updated_at in the Angular model.  I don't want my client to know about those items so I need to tell the server not to send those to the client.

I ended up with settling on restful_json and to keep it from sending everything, I ended up using active_model_serializers.  I created a serializer for each model such as this:

class BlogEntrySerializer < ActiveModel::Serializer
  attributes :id, :entry_name, :entry_text, :my_flag
end

Note that I did not include created_at and updated_at.  Hence my client doesn't know about these at all. Or another way to put it, the Angular models doesn't know about these attributes.  Thus, when I do an udpate, they don't get sent back to the server and restful_json will fill them in with appropriate values.



1 comment: