How to write an activemodel serializer for many, many relationships?

Trying to configure the backend for the ember-cli application. Here's what the models look like in Ember:

post.js

export default DS.Model.extend({
  heading: DS.attr('string'),
  content: DS.attr(''),
  imageUrl: DS.attr('string'),
  pageId: DS.belongsTo('page'),
  tagIds: DS.hasMany('tag')
});

tag.js

export default DS.Model.extend({
  name: DS.attr('string'),
  postIds: DS.hasMany('post')
});

Models in Rails and Active Record are just messages, tags, and topics. The subject is attached to the message and tag. (ex: Post has_many: tags via :: topics)

Here's what my serializers look like:

class PostSerializer < ActiveModel::Serializer
  embed :ids, include: true

  attributes :id, :heading, :content, :image_url

  has_many :tags
end

class TagSerializer < ActiveModel::Serializer
  embed :ids, include: true

  attributes :id, :name
end

This works in one direction: search messages will receive all tags. Doesn't work in another because I don't have has_many in TagSerializer. However, if I put has_many in both serializers, the stack level will be too high.

, , : " " ActiveModel? , - , Rails. . !

+4
1

, .

, includes Rails:

# posts controller
def show
  post = Post.includes(:tags).find_by id: params[:id]
  render json: post
end

# tags controller
def show
  tag = Tag.includes(:posts).find_by id: params[:id]
  render json: post
end

/ , :

# post serializer
def include_tags?
  object.association(:tags).loaded?
end

# tag serializer
def include_posts?
  object.association(:posts).loaded?
end

.

, , tagIds postIds ember tags posts.

+5

All Articles