【问题标题】:Using Rails Serializer in an EmberJS application for models在 EmberJS 应用程序中为模型使用 Rails 序列化程序
【发布时间】:2014-12-18 11:56:51
【问题描述】:

我有这两个模型:

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

一个是另一个的子类,因为我需要在不同的上下文中验证事物。


这是我使用序列化程序的方式:

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

问题在于 EmberJS 期望这样:

{"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"}}

而实际控制人给了我这个:

{"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"}}

有什么建议吗?

【问题讨论】:

    标签: ruby-on-rails activerecord ember.js model serialization


    【解决方案1】:

    您可以将根名称传递给控制器​​上的render json 调用。

    使用这样的序列化程序:

    class FooSerializer << ActiveModel::Serializer
        attributes :id
    

    通过FoosController 进行此呼叫

    render json: @foo, root: 'bar'
    

    给予:

    {"bar":{"id":1}...}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-21
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 2014-02-16
      • 2015-01-01
      • 1970-01-01
      相关资源
      最近更新 更多