[英]Rails ActiveRecord, selecting distinct fields from a joined table and returning all the models
[英]Rails 4 + ActiveRecord: How to merge data from 2 models?
我有2个模型,我需要从它们中加载数据,将加载的数据放入oen变量,然后对其进行遍历(模型模型具有不同的属性),如下所示:
cars = Car.order('created_at DESC').limit(10)
bikes = Bike.order('created_at DESC').limit(10)
@data = cars + bikes
然后在模型中,我想做这样的事情:
@data.order('created_at DESC).each do...
但事实是,上面一行中的排序不起作用。 如何根据created_at
列对两个模型中的数据进行排序?
第一个解决方案:
使用Rails STI(单表继承)。 为了使用它,您需要创建一个名为Vehicle
新模型(和表格),然后可以调用Vehicle.order('created_at DESC').limit(20)
。 您的模型类如下所示:
class Vehicle < ActiveRecord::Base; end
class Car < Vehicle; end
class Bike < Vehicle; end
第二种解决方案:
cars = Car.order('created_at DESC').limit(10)
bikes = Bike.order('created_at DESC').limit(10)
@data = (cars + bikes).sort_by{|vehicle| vehicle.created_at}.reverse
它不涉及对模型架构的任何更改,但是需要服务器端进行其他计算。
如果这些模型不同,则要遍历此类集合:
@data.each do |vehicle|
if vehicle.respond_to?(:sold_at)
vehicle.sold_at
end
#...
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.