Ruby Model Output Id as Object Oid

Ruby model output id as object oid

For guys using Mongoid 4+ use this,

module BSON
class ObjectId
alias :to_json :to_s
alias :as_json :to_s
end
end

Reference

Route to an object by id of related object

If the format of the url is flexible, I'd change it: domain.com/t2/v3

Then your route would look like:

get 't:type_id/v:version_id', :to => 'documents#show_version'

MongoDB/Mongoid: Can one query for ObjectID in embedded documents?

no, you can search only by field like { "routines._id" : ObjectId("4d1a7689fa87b17f50000020")}

A situation where ActiveRecord and SQL do not return the same results due to unknown OID being treated as String

You got this problem because ActiveRecord can't recognize this row as row from your account table. AR not parsing your sql and it's not sure what to do with anonymous cortage.

If you use find_by_sql your selected attributes not mapped to your model properly but still accessible, so try:

result.id
result.email

But you also have two ways to fix that.

First (it's very hackish but easy solution), transform your sql to Arel, that vaild for the scopes:

scope :unverified_with_no_associations, -> {
send(:default_scoped).from(Arel.sql("(SELECT * FROM accounts WHERE level = 0 AND id NOT IN
(SELECT DISTINCT(account_id) FROM verifications) AND id NOT IN
(SELECT DISTINCT(account_id) FROM positions) AND id NOT IN
(SELECT DISTINCT(account_id) FROM edits) AND id NOT IN
(SELECT DISTINCT(account_id) FROM posts) AND id NOT IN
(SELECT DISTINCT(account_id) FROM reviews) AND id NOT IN
(SELECT DISTINCT(sender_id) FROM kudos) AND id NOT IN
(SELECT DISTINCT(account_id) FROM stacks WHERE account_id IS NOT NULL))
AS accounts"))

... and call AR distinct method:

Account.unverified_with_no_associations.select(:id, :email).distinct

Second (it's much better solution):

Don't use sql directly. Rewrite your scope with Arel (https://github.com/rails/arel) or with squeel (https://github.com/activerecord-hackery/squeel)

Creating short, unique object id's in MongoDB

You may try to use first 4 bytes of ObjectID (they will represent timestamp).

But, to be 100% safe, it's better to produce really unique short id, by implementing a counter. You can use separate collection to maintain current value of your counter.

More details on mongo's ObjectID structure can be found here: http://www.mongodb.org/display/DOCS/Object+IDs

As an alternative you can convert convert hex string id representation to a representation based on 36 symbols (26 latin letters + 10 digits). It will obviously be shorter.

It seems, that there is a ruby library, that can do such conversions http://rubyworks.github.com/radix/

Add identifier for JSON array in Ruby on Rails

def index
@locations = Location.all
respond_with locations: @locations
end

Results in proper output



Related Topics



Leave a reply



Submit