Reputation: 12555
For my app I have three models: Quotes
, Images
, Videos
, all of them I consider content
. I want to call the index
action of my ContententController
to display a mix of these objects in JSON format. For example, I get something like this back.
[
{ ...image json... },
{ ...image json... },
{ ...video json... },
{ ...quote json... },
{ ...image json... }
]
How would I approach this? I feel like this has something to do with an SQL UNION? Thank you!
Upvotes: 0
Views: 127
Reputation: 548
def index
@quotes = Quotes.all
@images = Image.all
@videos = Video.all
@contents = @quotes + @images + @videos
format.json {render :json => @contents}
end
I think you can just append each object, but I wont recommend you to do that.
Upvotes: 0
Reputation: 1453
If you consider all three "content", then you really should use a single table inheritance strategy where they all inherit from the Content model. That way you can call
@Contents = Content.all.whatever
Instead of having to call each and then mix them together, or getting more complex then you need with the query. Turning them into JSON would then be easy considering each object would have its normal to_json method called on it, when doing something like this
format.json {render :json => @Contents}
Upvotes: 3