获取过去的最新事件和未来的最快事件的最佳方法是什么?
Client.rb:
has_many :events
Event.rb:
belongs_to :client
validates :starts_at, presence: :true
Clients_controller.rb:
@soonest_event = @client.events.where("starts_at >= ?", Time.zone.now).order("starts_at ASC").first.starts_at
@latest_event = @client.events.where("starts_at <= ?", Time.zone.now).order("starts_at DESC").first.starts_at
客户/节目:
Soonest event in the future:
= distance_of_time_in_words(Time.now, @soonest_event)
Latest event in the past:
= distance_of_time_in_words(Time.now, @latest_event)
如果客户端没有过去或将来的事件,则它会在控制器中显示错误,例如:
undefined method `starts_at' for nil:NilClass
1)如何提高代码效率?
2)我该如何解决错误?
答案 0 :(得分:0)
我用以下方法解决了它:
Client.rb:
def next_event
events.where("starts_at >= ?", Time.zone.now).order("starts_at ASC").pluck(:starts_at).first
end
def last_event
events.where("starts_at <= ?", Time.zone.now).order("starts_at DESC").pluck(:starts_at).first
end
客户/节目:
- if @client.last_event.present?
= distance_of_time_in_words(Time.now, @client.last_event)
- if @client.next_event.present?
= distance_of_time_in_words(Time.now, @client.next_event)