Search code examples
ruby-on-railsruby-on-rails-4active-model-serializers

Overriding association in ActiveModel Serializer - returns all attributes instead of serialized object attributes


I have 2 models : Repository and Branch, both of which have a corresponding serializer.

In RepositorySerializer, I want to list one default branch. Here's how I'm doing it:

attributes :id, :name, :ssh_url, :default_branch
has_many :branches

def default_branch
  object.branches.find_by_name(object.default_branch)
end

In BranchSerializer, I have:

attributes :id, :name

branches returns all branches properly serialized and only containing id and name attribute, but default_branch returns all the attributes of that branch.

Is there any way to utilize the existing BranchSerializer in this case or should I myself return the required attributes from the method default_branch.

Any help would be appreciated.


Solution

  • You're serializing default_branch as an attribute, so the BranchSerializer won't kick in. Add

      has_one :default_branch do
        object.branches.find_by_name(object.default_branch)
      end