Using Rails Serializer in an EmberJS application for models


#1

I’m using Ember latest and Ember-Data latest, along with Rails 4.2

I have these two models:

class DataSource < ActiveRecord::Base
  belongs_to :company
  has_many :deliveries
end

class DataSource::AsSubscriberSubmission < DataSource
  validates :company_id,
            :username,
            :password,
            :source_type, presence: true

  validates :source_type, inclusion: { in: ["First Party", "Third Party"] }
end

One is a subclass of the other, because I need to validate things in different contexts.


Here’s how I’m using the serializer:

class DataSourceSerializer < ApplicationSerializer
  attributes :id,
             :company_id,
             :source,
             :ad_server_name,
             :source_type,
             :pinged_at,
             :status,
             :username,
             :password        
end

class DataSource::AsSubscriberSubmissionSerializer < ApplicationSerializer
  attributes :id,
             :company_id,
             :source,
             :ad_server_name,
             :source_type,
             :pinged_at,
             :status,
             :username,
             :password
end

The problem is that EmberJS is expecting this:

{"data_source":{"id":97,"company_id":1211,"source":null,"ad_server_name":null,"source_type":"First Party","pinged_at":null,"status":null,"username":"asdfasdf","password":"asdfasdf"}}

And the actual controller is giving me this:

{"as_subscriber_submission":{"id":97,"company_id":1211,"source":null,"ad_server_name":null,"source_type":"First Party","pinged_at":null,"status":null,"username":"asdfasdf","password":"asdfasdf"}}

Any suggestions?


#2

Try adding a root 'data_source' to your serializer.


#3

That sounds like it makes sense, but I’m not sure where to place that. Can you give me an example? Infinitely grateful!


#4
class DataSource::AsSubscriberSubmissionSerializer < ApplicationSerializer
  root 'data_source'
end

Hope it helps.


#5

Thank you so much, worked like a charm. I really appreciate it!