Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

Should replace "_id" with "id" when calling to_json, to_xml, etc. #119

Open
chrisnicola opened this Issue Oct 3, 2011 · 4 comments

Comments

Projects
None yet
2 participants

This is also a problem in Mongoid and is fairly easy to work around but I was thinking this would be a nice improvement.

The fix is fairly simple

class CouchRest::Model::Base
  include ActiveModel::Serialization
  def serializable_hash(options = {})
    options[:except] ||= []
    options[:except].push :_id
    options[:methods] ||= []
    options[:methods].push :id
    super(options)
  end
end

The main reason for this is to play nice with some of the convention based javascript frameworks out there like backbone.js which expect to see an "id" attribute.

Ugh this is worse than I thought. The above fixes serializable_hash but doesn't affect as_json/to_json since those are being delegated by this:
https://github.com/couchrest/couchrest/blob/master/lib/couchrest/attributes.rb

Any suggestions on how to get this working properly?

So they say I'm slow cause I'm from Canada, eh?

Well I'm a bit of a Ruby noob so this took me a bit. This module solves the problem so if you like it let me know and I'll get a pull request sorted

https://gist.github.com/1258362

Owner

samlown commented Oct 3, 2011

Hi,

Sorry, but this really isn't a good idea ;-) You could end up with some major confusion converting _id to id all over the place!

In your specific case of backbone, all you need to do is add:

idAttribute: '_id'

to your Backbone models and the problem is solved; this is what I do in Rails. If you are dealing with requests direct to the database, like in node.js for example, you might want to checkout https://github.com/samlown/backbone-cradle which makes things a bit easier and works with couchrest_model.

Cheers, sam

Thanks Sam. I'll check this out. However there are still problems with the way as_json and to_json is delegated by CouchRest to it's Hash implementation. It makes it impossible to pass options or set default options (for example filtering out embedded documents) using overrides of serializable_hash. I still recommend looking at the Gist, even if you don't replace "_id" by default.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment