John Elent
John Elent

Reputation: 103

has_many through relation in active model serializers Rails API

I have many to many relation between users and projects through user_project. I know I could simply add has_many :projects in User Serializer (and vice versa in project serializer) to nest projects inside users.

But I also have a few additional fields in user_projects table (eg. start and end dates for user's participation in a corresponding project) and I have no idea what is the correct way to include them in the returned json. Should I create a special serializer for projects that are returned inside user with start_date included as a project's attribute or there's another way to do that?

Upvotes: 2

Views: 1394

Answers (2)

gnerkus
gnerkus

Reputation: 12019

The best way to do this would be to establish a 'has-many-through' (HMT) relationship between the user and project models and create a serializer for relationship's model.

class UserProjectSerializer < ActiveModel::Serializer
  ...
end

This will then be used in the UserSerializer via:

has_many :users_projects

The reason is that the relationship between the models contains additional data.

To implement the HMT, you'll need to create the user_projects model and define the HMT relationship in the related models:

users_project.rb

class UserProjects < ActiveRecord::Base
  belongs_to :user
  belongs_to :project
end

user.rb

class User < ActiveRecord::Base
  has_many: users_projects
  has_many: projects, through: :user_projects
end

project.rb

class Project < ActiveRecord::Base
  has_many: users_projects
  has_many: users, through: :user_projects
end

Upvotes: 1

dane
dane

Reputation: 631

I have had a similar problem before and I made use of rabl. There is a good tutorial on railscasts to help you get started.

Upvotes: 0

Related Questions