如何为活动模型序列化器关系选择所需的属性
我使用JSONAPI格式和Active Model Serializers来创建带有rails-api的api 。
我有一个序列化程序,它显示了一个具有许多topics
的特定post
,目前,在关系下,列出了这些主题。 它目前只列出id和类型。 我也想展示这个主题的标题。
有些人会说在我的控制器中使用include: 'topics'
,但我不需要完整的主题记录,只需要它的标题。
问题 :如何指定要从主题中显示哪些属性?
是)我有的
"data": { "id": "26", "type": "posts", "attributes": { "title": "Test Title 11" }, "relationships": { "topics": { "data": [ { "id": "1", "type": "topics" } ] } } }
我想要的是
"data": { "id": "26", "type": "posts", "attributes": { "title": "Test Title 11" }, "relationships": { "topics": { "data": [ { "id": "1", "type": "topics", "title": "Topic Title" } ] } } }
我目前的序列化程序类编辑:这就是我想要的。
class PostSerializer < ActiveModel::Serializer attributes :title belongs_to :domain belongs_to :user has_many :topics, serializer: TopicSerializer def topics # THIS IS WHAT I AM REALLY ASKING FOR end end class TopicSerializer < ActiveModel::Serializer attributes :title, :description belongs_to :parent has_many :children end
我尝试了一件事 – 下面有一个答案可以使这项工作,但它并不是我真正想要的。
class PostSerializer < ActiveModel::Serializer attributes :title, :topics belongs_to :domain belongs_to :user def topics # THIS WAS ANSWERED BELOW! THANK YOU end end
只需确保返回散列或散列数组,如下所示:
def videos object.listing_videos.collect do |lv| { id: lv.video.id, name: lv.video.name, wistia_id: lv.video.wistia_id, duration: lv.video.duration, wistia_hashed_id: lv.video.wistia_hashed_id, description: lv.video.description, thumbnail: lv.video.thumbnail } end end
而不是定义主题方法,最好定义单独的主题序列化程序,并明确指定您需要包含哪些属性。 这是更清晰,更可维护的方法,然后定义主题方法。
class PostSerializer < ActiveModel::Serializer attributes :title belongs_to :domain belongs_to :user # remember to declare TopicSerializer class before you use it class TopicSerializer < ActiveModel::Serializer # explicitly tell here which attributes you need from 'topics' attributes :title end has_many :topics, serializer: TopicSerializer end
同样,尽量避免尽可能地定义关系的方法,它不干净,既不可维护。
- 渴望与Active Model Serializers加载关联
- 版本控制ActiveModel :: Serializer
- <NoMethodError:#Record :: ActiveRecord_Relation的未定义方法`read_attribute_for_serialization':
- 使用Rspec测试ActiveModel :: Serializer类
- 活动模型序列化器和自定义JSON结构
- 控制器中的索引方法不适用于活动模型序列化程序
- 活动模型序列化程序belongs_to
- Url Helper在ActiveModelSerializer 0.10.0中?
- 使用active_model_serializers序列化权限(例如CanCan)