我需要在JSON响应中公开inheritance_column,这样我就可以在我的前端(Angular)应用程序中检索它。我怎么才能让它成为现实呢?
我已经搜索了很多次来寻找这个问题的答案,但是我没有找到它!
在我的案例中,我的用户可以是Admin、Employee或Customer。唯一的区别是Customer比Admin和Employee多了两个字段。这就是我决定实现STI的原因。如果我做了一个错误的选择,请随时告诉我。
我的user_serializer.rb示例:
class UserSerializer < ActiveModel::Serializer
attributes :id, :name, :email, :type
end

我的user.rb在/models中
我的users_controllers.rb在控制器/api/v1/中
更新:
我的控制器:
class Api::V1::UsersController < Api::V1::BaseApiController
before_action :authenticate_user!
# some methods...
def show
user = User.find(params[:id])
if user.present?
render json: { data: user }, status: 200
else
head 404
end
end
# some methods...
private
def user_params
params.require(:user).permit(
:id,
:name,
:email,
:password, :password_confirmation,
:registration,
:cpf,
:landline, :cellphone, :whatsapp,
:simple_address,
:public_agency_id,
:public_office_id,
:type
)
end
end我的模型:
class User < ApplicationRecord
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
include DeviseTokenAuth::Concerns::User
# belongs_to :address
attr_accessor :skip_password_validation
validates :name, presence: true
validates :type, presence: true
scope :admins, -> { where(type: 'Admin') }
scope :employees, -> { where(type: 'Employee') }
scope :customers, -> { where(type: 'Customer') }
# CALLBACKS
before_validation :generate_uuid!
before_create :downcase_email
def password_required?
return false if skip_password_validation
super
end
def token_validation_response
{
id: id,
email: email,
name: name,
surname: surname,
cpf: cpf,
landline: landline,
cellphone: cellphone,
whatsapp: whatsapp,
simple_address: simple_address,
created_at: created_at,
updated_at: updated_at,
type: type
}
end
private
def generate_uuid!
self.uid = SecureRandom.uuid if self.uid.blank?
end
def downcase_email
self.email = self.email.delete(' ').downcase
end
end响应对象示例:

关于config/initializers/active_model_serializer.rb,,我的项目中没有这样的文件。
发布于 2018-05-24 02:48:52
我认为我们需要更多关于控制器、模型、初始化器和JSON输出的信息来准确诊断这个问题。不过,我还是试一试可能会有帮助。
总体而言,看起来您可能没有加载UserSerializer。我建议将其移动到序列化程序的根目录中,并在那里工作:然后,如果您出于某种原因想要将其移动到api/v1,您可以专注于可能会挂起问题的名称空间问题。
# app/serializers/user_serializer.rb
class UserSerializer < ActiveModel::Serializer
attributes :id, :name, :email, :type
end如果这样可以工作,那么像get /users/:id这样的调用应该会返回如下内容:
{ "id": 1, "name":"Bill Gates", "email":"bigcheese@microsoft.com", "type": "Employee" } 您可能还需要更新应用程序控制器以进行序列化:
class ApplicationController < ActionController::API
include ActionController::Serialization
# ...
end下面是一些可能会有帮助的资源:
https://stackoverflow.com/questions/50478614
复制相似问题