繁体   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