我有4个名为startStopId,startStopId1,endStopId,endStopId2
我按如下所示进行查询
sql = "select A.bus_id as busid, A.stop_id as source, A.arrival as atime, B.arrival as dtime from
(SELECT * from schedules as S where S.stop_id = #{startStopId}) A
inner join
(SELECT * from schedules as S where S.stop_id = #{endStopId}) B
on A.bustag = B.bustag
where A.arrival < B.arrival
and A.arrival > '#{@finalTime}'"
@possible_buses = ActiveRecord::Base.connection.execute(sql)
此查询可能会返回nil
,在这种情况下,我会首先尝试startStopId
,endStopId2
,如果返回nil
,我会尝试另一个我有4个值的组合。
我想知道在红宝石中是否有一种优雅的方式。我在想我可以将这个查询放在一个方法下并传递不同的组合。但如果有经验的红宝石可以提供一种方法,我将不胜感激。
答案 0 :(得分:0)
对于初学者,我会选择更具表现力的变量名称,因为我不确定每个变量名称到底是什么。
此查询可能会返回nil
这听起来像是Null对象模式的一个很好的例子。从本质上讲,从查询返回的任何内容都可以传递给类的构造函数。然后,该类可以确定应该返回什么,是否只是查询的值,或者如果查询的值是nil
,则返回某个预定值。使用这种模式通常意味着拥有一个类似NullBusID
的类,代表什么都没有。
有关Null对象模式的更多信息:
http://confreaks.tv/videos/bathruby2015-nothing-is-something
https://robots.thoughtbot.com/rails-refactoring-example-introduce-null-object