簡體   English   中英

通過表迭代以顯示datetime> = Today.now的下一條記錄

[英]Iterate through a table to display the next record with the datetime >= Today.now

我正在嘗試遍歷我的日程表並獲得一條帶有'datetime:> = Time.now'的記錄來顯示當前團隊的下一場比賽。

這是我的團隊模型:

class Team < ActiveRecord::Base
  attr_accessible :city, :conf, :div, :full_name, :name, :short_name

  has_many :fans
  has_many :away_schedules, class_name: 'Schedule', foreign_key: :away_team_id
  has_many :home_schedules, class_name: 'Schedule', foreign_key: :home_team_id

 def schedules
  (away_schedules + home_schedules).sort_by(&:id)
  end
end

這是我的日程表模型:

class Schedule < ActiveRecord::Base  
  attr_accessible :away_team_id, :datetime, :home_team_id, :season, :week

  belongs_to :away_team, class_name: 'Team'
  belongs_to :home_team, class_name: 'Team'
end

我有一個games_helper.rb

module GamesHelper
  def current_game
   @current_game = current_fan.team.schedules
  end
end

我有一個部分_scoreboard.html.erb

<% current_game.each do |game| %>
  <% if game.datetime.to_s >= Time.now.to_s %>
  <% return current_game = game.datetime.to_s(:custom),
  game.away_team.short_name, " @ ", game.home_team.short_name %>
  <% end %>
<% end %>

這似乎有效但是使用return在結果的括號內有數組:

["Sun, Sep 15th, at 4:25 PM", "DEN", " @ ", "NYG"]

希望它顯示:

Sun, Sep 15th, at 4:25 PM, DEN @ NYG

我不確定我是否正確地走這條路。

假設一個名為'Game'的ActiveRecord模型帶有一個名為'game_date'的字段:

Game.game_date.where('game_date > ?', Time.now).order('game_date').first

這將確保您的數據庫執行排序和搜索,並且只返回一條記錄。 如果你不喜歡占位符語法,那么squeel gem可以使它看起來更加紅寶石,盡管這個例子可能有些過分。

更新 (根據問題的變化)

我想你想把很多ruby代碼從部分移動到你的幫助器。 在您的助手中,添加以下方法:

def current_game_scoreboard(game)
  if game.datetime >= Time.now
    current_game = game.datetime.to_s(:custom),
      game.away_team.short_name, " @ ", game.home_team.short_name
    return current_game.join('')
  end
end

在你的部分只是替換具有上述代碼的循環體:

current_game_scoreboard(game)

你可以通過將一個集合傳遞給記分板部分並使用Rails的部分魔法來進行循環迭代來進一步改進這一點,但這將使你朝着正確的方向前進。

你可以用紅寶石做到這一點: -

require 'date'

dtar = [ "2013-8-15 13:00:00", "2013-9-15 13:00:00","2013-12-15 13:00:00", "2013-12-5 13:00:00"]
dtar.map{|d| Date.parse d}.find{|d| d > Date.today}
# => #<Date: 2013-09-15 ((2456551j,0s,0n),+0s,2299161j)>

將一個名為next_game的方法添加到Team模型中

class Team < ActiveRecord::Base
  def next_game(reload=false)
    @next_game = nil if reload
    @next_game ||= schedules.where('game_date > ?', Time.now).order('game_date').first
  end

  # change the schedules method implementation so that you can perform all the work in db
  def schedules
    Schedule.where("away_team_id = ? OR home_team_id = ?", id, id)
  end
end

添加幫助以顯示游戲信息

module GamesHelper
  def game_info g
    "#{g.datetime.to_s(:custom)}, #{g.away_team.short_name} @ #{g.home_team.short_name}"
  end
end

現在在你看來:

<% if (game = current_fan.team.next_game).present? %>
  <%= game_info(game)%>
<% end %>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM