将 ID/类添加到 Rails link_to 的更好更简洁的方法?
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
出于这个原因,
link_to
方法采用选项:您甚至可以添加条件来有选择地触发它:
如果您有一个 Race 方法来指示它是否是当前的,您甚至可以折叠它:
这很容易在您的模型并可以在其他地方使用:
将其放入模型中可以使测试变得更加容易。
The
link_to
method takes options for this very reason:You can even add conditions to trigger it selectively:
You can even collapse this if you have a method for Race that indicates if it's current:
This is easily implemented in your model and can be used in other places:
Having it in the model makes it significantly easier to test.