Rails的新东西......我已经创建了一个帮助格式化种族名称和帮助他们的约会。如果存在条件,我需要传递:id => "current-race"
(基本上如果事件现在发生)。我怎么能这样做?
def formatted_race_dates(race)
link_to (race.homepage) do
raw("<strong>#{race.name}</strong> <em>#{race_dates_as_string(race)}</em>")
end
end
现在race.start_date < Date.today && race.end_date > Date.today
时我想在链接中添加id="current-race"
。
我通常会设置if / else条件并将其格式化为两种方式。但似乎必须有一个我不知道的Ruby技巧来简化某些内容,就像在列表中将{id> /类添加到一个link_to
一样?即使没有条件,我也不太确定在何处/如何添加:id => "current-race"
。
我不知道的那么多Ruby / Rails技巧......一切都有帮助!
答案 0 :(得分:10)
由于这个原因,link_to
方法采用了选项:
link_to(race.homepage, :id => 'current-race') do ...
您甚至可以添加条件来有选择地触发它:
link_to(race.homepage, :id => (race.start_date < Date.today && race.end_date > Date.today) ? 'current-race' : nil) do ...
如果您有Race的方法指示它是否是最新的,您甚至可以折叠它:
link_to(race.homepage, :id => race.current? ? 'current-race' : nil) do ...
这可以在您的模型中轻松实现,并可以在其他地方使用:
def current?
self.start_date < Date.today && self.end_date > Date.today
end
在模型中使用它会使测试变得更加容易。