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!
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.
精彩评论