繁体   English   中英

rails params [:month]剥离前导零导致不正确的匹配

[英]rails params[:month] stripping leading zeros causing incorrect match

在我的应用程序中,当用户访问finances/trends/2014/03 trends_controller在我的trends_controller执行选择查询

@expenses = Expense.select("name, amount, id, created_at").where(:user_id => current_user.id).where(["strftime('%Y', created_at) = ? AND strftime('%m', created_at) = ?", params[:year], params[:month] ])
@expenses_by_month = @expenses.group_by { |expense| expense.created_at.beginning_of_month }

如果查询返回结果,则呈现页面,否则发生重定向。 这一切似乎都很好。

当我尝试将params[:month]传递到索引页面上的链接中时,会出现问题,并且:month中的前导零似乎被剥夺了,因此该链接将返回诸如finances/trends/2014/3而不是select语句所需的finances/trends/2014/03 2014/03(因为在数据库中,created_at值的存储时间当然是2014-03天)。

路线:

get "finances/trends/:year/:month" => "trends#month", :as => :month_trends

index.html.erb:

<% @expenses_by_month.each do |month, expenses| %>
<%= link_to "#{month.strftime('%B')}", month_trends_path(:year => month.year, :month => month.month) %>
<% end %>

我知道select语句中的%m应该将月份作为填充值返回,因此我完全不知道是什么原因造成的。

如果可行,请尝试一些直接的红宝石方法。 这是怎么

"3".rjust(2,"0") #=> 03
"3".ljust(2,"0") #=> 30

month=3
month.to_s.rjust(2,"0") #=> 03

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM