簡體   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