Created
April 2, 2014 22:53
-
-
Save bradynpoulsen/9944962 to your computer and use it in GitHub Desktop.
ActiveModel Serializer Embedded Associations via ?embed=rel1,rel2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Project < ActiveRecord::Base | |
belongs_to :client | |
has_many :user_projects | |
has_many :users, through: :users_projects | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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