I’m building an API with Rails 3, using devise to handle some of the authentication.
I commonly use the respond_with method to return xml/json for various resources.
Eg GET /groups.xml will route to
def index
respond_with Group.all
end
This works fine across my site for various resources, and returns nicely formatted json or xml containing all the attributes of each group.
However, when I call GET /users.xml, it only responds with a limited subset of the each user’s attributes. It turns out that only attributes defined in attr_assessible will be returned here – I suspect this is a “feature” of devise, because it’s not the case for any other model.
Can anyone enlighten me?
Edit: This is sort of fixed in Devise 1.4.2. See below for details
Older versions ( < 1.4.2) of Devise performed a monkeypatch on the to_json and to_xml methods, overwriting the :only => [] option with the attributes defined in attr_accessible. Annoying.
This has now been changed, so that serializable_hash is overwritten instead, and any :only => [:attribute] options set in to_json or to_xml are persisted.
In my case, I ended up monkeypatching to_json myself, and adding a method api_accessible to all ActiveRecord models.
This means that you can now define a list of attributes (and methods!) that will be exposed by default when calling to_json. Respond_with also uses to_json, so it works well for APIs.
Eg, user.rb