2
votes

I have a Task model that looks like this:

class Task
   # has a title
   belongs_to :owner, class_name: "User"
   belongs_to :asignee, class_name: "User
end

And a Sprint with a json field metadata:

create_table :sprints, id: :uuid do |t|
  t.json :metadata
end

class Sprint
    def close_sprint
        self.metadata = serialized_tasks
        self.save
    end
end

I'm using active model serializers to serialize sprint tasks like this:

def serialized_tasks
   ActiveModel::Serializer::CollectionSerializer.new(self.tasks, serializer: TaskSerializer).to_json
end

The problem is that it stores the tasks data as a json string and not as a json object.

The serializer looks like this:

class TaskSerializer < ActiveModel::Serializer
  attributes :title, :owner_name, :created_at, :status, :asignee_name, :asignee_email

  def owner_name
    object&.owner&.full_name
  end

  def asignee_name
    object&.asignee&.full_name
  end

  def asignee_email
    object&.asignee&.email
  end
end

How can I get a valid JSON object to be stored in a rails json field using active_model_serializers? If it's not possible, how can I query the associated data as a valid JSON object to store in the metadata field?

1

1 Answers

0
votes

I was able to get the hash I needed using as_json instead of to_json.

as_json(options = nil)

Returns a hash representing the model. Some configuration can be passed through options.

The option include_root_in_json controls the top-level behavior of as_json. If true, as_json will emit a single root node named after the object's type. The default value for include_root_in_json option is false.