Paweł Dawczak
Paweł Dawczak

Reputation: 9639

Better way of building urls

I have a route configured like this:

get "calendar/:year/:month" => "calendar#month", as: :calendar_month

To create links for "next" month and "previous" month, this is what you need to use in your template:

<%= link_to "Next", calendar_month_path(year: @date.next_month.year, month: @date.next_month.month) %>

or a bit simpler:

<%= link_to "Previous", calendar_month_path(@date.prev_month.year, @date.prev_month.month) %>

Both feel a bit verbose.

Is there any way to take advantage of that the @date.prev_month/@date.next_month return an object (Date) that has methods which respond to defined in route params (:year, :month)?

Something similar to:

<%= link_to "Previous", calendar_month_path(@date.prev_month) %>

Would be an ideal solution, but it doesn't work.

How do you deal with similar situations?

Thank you for any advice!

Upvotes: 1

Views: 46

Answers (1)

Shadwell
Shadwell

Reputation: 34774

You can always add a method in your helpers to convert the date to a calendar_month_path:

def path_for_date(d)
  calendar_month_path(d.year, d.month)
end

Which means your links are:

link_to("Previous", path_for_date(@date.prev_month)
link_to("Next", path_for_date(@date.next_month)

Depending on your other routes you may want to name it a bit better than I have but you get the idea.

Upvotes: 2

Related Questions