Skip to content

Instantly share code, notes, and snippets.

@bradynpoulsen
Created April 2, 2014 22:53
Show Gist options
  • Save bradynpoulsen/9944962 to your computer and use it in GitHub Desktop.
Save bradynpoulsen/9944962 to your computer and use it in GitHub Desktop.
ActiveModel Serializer Embedded Associations via ?embed=rel1,rel2
class Project < ActiveRecord::Base
belongs_to :client
has_many :user_projects
has_many :users, through: :users_projects
end
class ProjectSerializer < ActiveModel::Serializer
embed :ids, include: true
attributes :id, :name
has_one :client
# Has Many
has_many :user_projects
has_many :users
# Set to only include if passed (by CSV) in ?embed=
# Notice how `client` is not included in this loop; `client` will always be embedded
%w(user_projects users).each do |assoc|
class_eval <<-RUBY_EVAL, __FILE__, __LINE__+1
def include_#{assoc}?
scope[:embed] && scope[:embed].split(','),include?("#{assoc}")
end
RUBY_EVAL
end
end
class ProjectsController < MyApiBaseController
serialization_scope :params # Set value of params to the `scope` method in our serializer
inherited_resources # launch le-hack for InheritedResources
actions :all
def permitted_params
params.permit project: [:name, :client_id]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment