1

So I have a many to many relationship. I am storing a status string on the join table.

Example: Order has many Items on it. Items are fixed. On the OrdersItems table we store a string called item_status. I want to return the Order using as_json.

  def as_json(options={})
    opts = {
      only: PUBLIC_ATTRIBUTES,
      methods: [:items],
    }.merge(options){|k,o,n|o|n}
    super(opts)
  end

This works, except I want to add that item_status to each hash in the items array. How can I do this?

1 Answer 1

1

You can include associated models as part of the options given to to_json, with more or less the same configuration options.

opts = {
  only: PUBLIC_ATTRIBUTES,
  include: {
    items: {
      only: [:status]
    }
  }
}

See: https://apidock.com/rails/ActiveRecord/Serialization/to_json

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.