遍历表格以显示日期时间> = Today.now的下一条记录

时间:2013-09-06 19:33:25

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.2

我正在尝试遍历我的日程表,并使用'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

我不确定我是否会以正确的方式解决这个问题。

3 个答案:

答案 0 :(得分:2)

假设一个名为'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的部分魔术来进行循环迭代来进一步改进这一点,但这将使你朝着正确的方向前进。

答案 1 :(得分:0)

您可以在ruby中执行此操作: -

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)>

答案 2 :(得分:0)

将名为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 %>