构建 url 的更好方法
Better way of building urls
我有这样配置的路由:
get "calendar/:year/:month" => "calendar#month", as: :calendar_month
要为 "next" 月和 "previous" 月创建链接,您需要在模板中使用以下内容:
<%= link_to "Next", calendar_month_path(year: @date.next_month.year, month: @date.next_month.month) %>
或者更简单一点:
<%= link_to "Previous", calendar_month_path(@date.prev_month.year, @date.prev_month.month) %>
两者都感觉有点冗长。
有什么方法可以利用 @date.prev_month
/@date.next_month
return 一个对象 (Date
),它具有响应路由参数中定义的方法(:year
, :month
)?
类似于:
<%= link_to "Previous", calendar_month_path(@date.prev_month) %>
这将是一个理想的解决方案,但它不起作用。
你如何处理类似情况?
感谢您的任何建议!
你总是可以在你的助手中添加一个方法来将日期转换为 calendar_month_path
:
def path_for_date(d)
calendar_month_path(d.year, d.month)
end
这意味着您的链接是:
link_to("Previous", path_for_date(@date.prev_month)
link_to("Next", path_for_date(@date.next_month)
根据你的其他路线,你可能想给它起一个比我更好的名字,但你明白了。
我有这样配置的路由:
get "calendar/:year/:month" => "calendar#month", as: :calendar_month
要为 "next" 月和 "previous" 月创建链接,您需要在模板中使用以下内容:
<%= link_to "Next", calendar_month_path(year: @date.next_month.year, month: @date.next_month.month) %>
或者更简单一点:
<%= link_to "Previous", calendar_month_path(@date.prev_month.year, @date.prev_month.month) %>
两者都感觉有点冗长。
有什么方法可以利用 @date.prev_month
/@date.next_month
return 一个对象 (Date
),它具有响应路由参数中定义的方法(:year
, :month
)?
类似于:
<%= link_to "Previous", calendar_month_path(@date.prev_month) %>
这将是一个理想的解决方案,但它不起作用。
你如何处理类似情况?
感谢您的任何建议!
你总是可以在你的助手中添加一个方法来将日期转换为 calendar_month_path
:
def path_for_date(d)
calendar_month_path(d.year, d.month)
end
这意味着您的链接是:
link_to("Previous", path_for_date(@date.prev_month)
link_to("Next", path_for_date(@date.next_month)
根据你的其他路线,你可能想给它起一个比我更好的名字,但你明白了。