簡體   English   中英

如何在Rails(ActiveRecord)中傳遞不在模型中的Serializer中的屬性?

[英]How to pass attributes in Serializer not in model in Rails (ActiveRecord)?

我正在構建一個包含UsersSightingsComments的Rails后端。 模型Comment加入SightingUser 我想將用戶的名稱或用戶名以及user_id傳遞給我的前端,后者是CommentSerializer中連接表Comments的屬性。

我可以使用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

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

def user_name object.user.name end

在CommentSerializer類中

所以我在我的Serializer文件中運行此方法以傳遞此屬性:

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

結束

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM