[英]How to pass attributes in Serializer not in model in Rails (ActiveRecord)?
我正在構建一個包含Users
, Sightings
和Comments
的Rails后端。 模型Comment
加入Sighting
和User
。 我想將用戶的名稱或用戶名以及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.