将 ID/类添加到 Rails link_to 的更好更简洁的方法?

发布于 2024-11-09 06:48:10 字数 657 浏览 2 评论 0原文

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 我想将 id="current-race" 添加到链接中。

我通常会设置一个 if/else 条件并以两种方式格式化它。但似乎一定有一个我不知道的 Ruby 技巧来简化某些事情,例如将 id/class 添加到列表中的一个 link_to ?即使没有条件,我也不太确定在哪里/如何添加 :id =>; “当前种族”

这么多我不知道的 Ruby/Rails 技巧...一切都有帮助!

New-ish to Rails... I've created a helper to format race names & their dates. I need to pass :id => "current-race" if a condition is present (basically if event is happening now). How could I go about this?

def formatted_race_dates(race)
    link_to (race.homepage) do
      raw("<strong>#{race.name}</strong> <em>#{race_dates_as_string(race)}</em>")
    end
end

now when race.start_date < Date.today && race.end_date > Date.today I'd like to add id="current-race" to the link.

I would normally set up an if/else condition and format it two ways. But seems there must be a Ruby trick I don't know to simplify something as common adding of a id/class to one link_to in a list? Even without the condition I'm not quite sure where/how to add :id => "current-race".

So many Ruby/Rails tricks I don't know...everything helps!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

墟烟 2024-11-16 06:48: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

将其放入模型中可以使测试变得更加容易。

The link_to method takes options for this very reason:

link_to(race.homepage, :id => 'current-race') do ...

You can even add conditions to trigger it selectively:

link_to(race.homepage, :id => (race.start_date < Date.today && race.end_date > Date.today) ? 'current-race' : nil) do ...

You can even collapse this if you have a method for Race that indicates if it's current:

link_to(race.homepage, :id => race.current? ? 'current-race' : nil) do ...

This is easily implemented in your model and can be used in other places:

def current?
  self.start_date < Date.today && self.end_date > Date.today
end

Having it in the model makes it significantly easier to test.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文