【问题标题】:Rails 4.2 + ActiveModel Serializer 0.8.3Rails 4.2 + ActiveModel 序列化器 0.8.3
【发布时间】:2015-03-25 05:06:39
【问题描述】:

我有这些文件,我可以让 ActiveModel Serializer 工作。

# 
# congif/routes.rb
namespace :dealer do
  resources :users do
    resources :orders do
      get 'search_dealer_profile', on: :collection
# 
# app/serializers/profile_serializer.rb
class  ProfileSerializer < ActiveModel::Serializer
  attributes :id
end
# 
# app/controllers/dealer/orders_controller.rb
class Dealer::OrdersController < Dealer::BaseController
  def search_dealer_profile
    profile = Profile.where(id: params[:id]).first

    # I tried
    # 
    # => Return a Json without use AMS. Object {id: 4, user_id: 4, name: "Alex", surname: "Sensation"…}
    render json: profile 

    # => Works in console but here I get this : uninitialized constant Dealer::OrdersController::ProfileSerializer
    render json: ProfileSerializer.new(profile).as_json 
  end

我想要的json

{:profile=>{:id=>4}} 

我正在使用

  • Rails 4.2.0
  • active_model_serializer 0.8.3

谁能帮帮我?

【问题讨论】:

  • 你现在得到什么格式?
  • 如果我使用 render json: profile 它会返回一个完整的配置文件 json 对象:{id: 4, user_id: 4, name: "Alex" ... + 所有属性个人资料

标签: ruby-on-rails-4 active-model-serializers


【解决方案1】:

看起来 ProfileSerializer 类没有被加载。确保 app/serializers 包含在配置自动加载路径中。

application.rb

config.autoload_paths << Rails.root.join('app', 'serializers')

【讨论】:

    猜你喜欢
    • 2017-10-28
    • 2018-04-23
    • 1970-01-01
    • 2015-11-02
    • 1970-01-01
    • 2015-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多