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.
class ActiveRecord::Base
def to_json(options = {}, &block)
if self.class.respond_to?(:api_attributes)
super(build_serialize_options(options), &block)
else
super(options, &block)
end
end
class << self
attr_reader :api_attributes
def api_accessible(*args)
@api_attributes ||= []
@api_attributes += args
end
end
private
def build_serialize_options(options)
return options if self.class.api_attributes.blank?
methods = self.class.instance_methods - self.class.attribute_names.map(&:to_sym)
api_methods = self.class.api_attributes.select { |m| methods.include?(m) }
api_attrs = self.class.api_attributes - api_methods
options.merge!(only: api_attrs) if api_attrs.present?
options.merge!(methods: api_methods) if api_methods.present?
return options
end
end
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
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable, :confirmable,
:recoverable, :rememberable, :trackable, :validatable
#Setup accessible (or protected) attributes for your model
attr_accessible :email,
:password,
:password_confirmation,
:remember_me,
:first_name,
:last_name,
api_accessible :id,
:name,
:created_at,
:first_name,
:last_name,
:some_model_method_also_works
end