我正在Rails应用程序中处理一个普通的Ruby类。
对于total_leg_count方法来说--这是实现我想要的目标的最好方法吗?我觉得有更好的办法。
class AircraftTimeReport
...
def total_leg_count
count = 0
active_flights_within_timeframe.includes(:legs).each do |flight|
count += flight.legs.size
end
count
end
private
def active_flights_within_timeframe
@aircraft.flights.within_timeframe(from_datetime, to_datetime).not_cancelled
end
end
report = AircraftTimeReport.new(@aircraft)
puts report.total_leg_count一架飞机has_many航班和一架飞行belongs_to飞机。
飞行has_many腿和腿belongs_to飞行。
我见过其他使用Arel或普通SQL的解决方案,但我似乎无法理解它。
而且,我发现很难对这个方法进行单元测试,这就是为什么我想知道是否有更好的方法!
发布于 2015-08-22 07:45:35
等价物,但功能和习惯用法:
def total_leg_count
active_flights_within_timeframe.includes(:legs).map { |fl| fl.legs.size }.sum
end这个纯SQL查询应该是等价的,更具有表现力:
def total_leg_count
active_flights_within_timeframe.includes(:legs).count(:legs)
endhttps://codereview.stackexchange.com/questions/101611
复制相似问题