如何在Rails(ActiveRecord)中传递不在模型中的Serializer中的属性?

问题描述 投票:0回答:2

我正在建立一个有UsersSightingsComments的Rails后端。 modelComment加入SightingUser。我想将用户的名字或用户名以及user_id传递给我的前端,user_id是Comments中连接表CommentSerializer的一个属性。

我可以使用Active Record或Ruby方法访问这些数据,但实际上如何使这个属性通过Serializer传递?

这是我的CommentSerializer文件:


class CommentSerializer < ActiveModel::Serializer

  attributes :id, :body, :likes, :user_id

  belongs_to :commentable, :polymorphic => true
  belongs_to :sighting
  has_many :comments, as: :commentable
end

ruby-on-rails activerecord attributes serializer
2个回答
0
投票

添加到您的属性:user_name例如然后添加

def user_name object.user.name end

在CommentSerializer类中


0
投票

所以我在我的Serializer文件中运行此方法以传递此属性:

  def user_name
 User.all.find { |f| f.id == object.user_id }.username 

结束

© www.soinside.com 2019 - 2024. All rights reserved.