Jensky
Jensky

Reputation: 917

How to get id from Mongoid in Angular?

I uses Rails 4 and MongoDB by Mongoid gem. I have Angular template like this:

<ul><li><a href="" ng-click="navNewEmail()">Add a new post</a></li></ul>

<section>
  <h1>Availabe templates: (click to load content)</h1>
  <div ng-repeat="email in data.emails">
      <h3><a href="" ng-click="viewEmail(email._id)">{{ email.subject }}</a> - author: {{ email.user_name }}</h3>
{{ email._id }}
  </div>
</section>

How can I get a id of my Email object? I have simple Email object in MongoDB. I tried email._id but Angular display nothing.

Everything works besides {{ email._id }} part.

Log from JavaScript console:

$$hashKey   
    "005"

_id     
    Object { $oid="5478774a6a61734d8a000000"}

body        
    "Here is the sample conte...le ble ble. Nice email."

subject     
    "This is first template"

user_name       
    null

So _id is the object. How can I convert it into string and display in angular template?

I do something like this:

  {{ email._id.$oid }}

I don't know is it correct but works.

Upvotes: 0

Views: 1345

Answers (1)

East2d
East2d

Reputation: 2096

I think that you can serialize json object in rails side using 'active_model_serializers' gem.

gem "active_model_serializers", github: "rails-api/active_model_serializers"

and create your own serializer in serializers directory

class EmailSerializer < ActiveModel::Serializer
  attributes :_id, :body, :subject, :user_name
end

then, try to use {{email._id}}

so, I think that active_model_serializers calls object._id.to_s method automatically when it performs serialization.

Upvotes: 1

Related Questions