I need to render the itinerary json but consolidating all todos as a single json array nested inside:
render json: @itinerary, include: {
places: {
only: [:id, :title],
include: {
todos: {
only: [:id, :content],
include: :todo_type
},
place_category: {
include: {
todos: {
only: [:id, :content],
include: :todo_type
}
}
},
climate: {
include: {
todos: {
only: [:id, :content],
include: :todo_type
}
}
}
}
}
}
I wish to render all todos together, so that the client doesn't have to do the consolidate all todos, removing duplicates and doing other work on it.
So I created a method consolidated_todos
in place
model
def considated_todos
todos = self.todos
todos += self.place_category.todos
todos += self.climate.todos
todos
end
And then changed my render method to the following
render json: @itinerary, include: {
places: {
only: [:id, :title],
include: :place_category,
methods: [:consolidated_todos],
}
}
How do I add
:include
(:todo_type, etc.,) ,:only
(:id, :content, etc.,) and:except
for hashes returned from:methods
?
I need to do something like methods: [ consolidated_todos: { include: :todo_type } ]
.
EDIT :
This question is NOT about
but is specifically about using include
for hashes returned from :methods
or an equivalent short workaround (instead of using as_json
) for the same
I don't think you can, and even you could, you probably should be creating different methods where you select data that you need and then them when you render the object. It will be easier to read and maintain.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.