Reputation: 409
I'm working with two tables Video and Picture and I would like to regroup them using SQL instead of ruby. This is how I do it now :
@medias = (Video.all + Picture.all).sort_by { |model| model.created_at }
Is their a way to do the same thing only with SQL/ActiveRecord?
Upvotes: 0
Views: 111
Reputation: 346
Since you don’t have the same columns in each model you could create a polymorphic relationship with a new model called media. Your Videos and Pictures would be associated with this new model and when you need to work on only your media you don’t need to worry about whether it is a video or a picture. I’m not sure if this fits into your schema and design since there is not much info to go on from your post but this might work if you wanted to take the time to restructure your schema. This would allow you to use the query interface to access media. See the Rails Guide here:
http://guides.rubyonrails.org/association_basics.html#polymorphic-associations
You can create a media model with all the fields need to satisfy a Video or Picture object. The media model will also have a type field to keep track of what kind of media it is: Video or Picture.
Upvotes: 2
Reputation: 35
To run sql queries in Rails you could do this:
sql_statement = "Select * from ..."
@data = ActiveRecord::Base.connection.execute(sql_statement)
Then in your view you could simply reference the @data object
Upvotes: 0
Reputation: 2051
Yes, using ActiveRecord's #order
:
@video = Video.order(:created_at)
@pictures = Picture.order(:created_at)
@medias = @video.all + @pictures.all # Really bad idea!
Also calling all
on the models like that will unnecessarily load them to memory. If you don't absolutely need all records at that time, then don't use all
.
Upvotes: 1