我正在建立一个有Users
,Sightings
和Comments
的Rails后端。 modelComment
加入Sighting
和User
。我想将用户的名字或用户名以及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
添加到您的属性:user_name例如然后添加
def user_name object.user.name end
在CommentSerializer类中
所以我在我的Serializer文件中运行此方法以传递此属性:
def user_name
User.all.find { |f| f.id == object.user_id }.username
结束