简体   繁体   中英

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

In my application when a user visits finances/trends/2014/03 a select query is executed in my 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 }

and if the query returns results, the page is rendered, otherwise a redirect occurs. This all seems to work fine.

The problem occurs when I attempt to pass the params[:month] into a link on my index page, and the leading zero in the :month seems to get stripped, so the link will return a path such as finances/trends/2014/3 instead of the required finances/trends/2014/03 for the select statement (because in the db, the created_at value is stored as 2014-03-day, of course).

routes:

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 %>

I understand that the %m in the select statement should return the month as a padded value, so I'm not sure at all what is causing this.

Try some direct ruby way, if that works. Here is how

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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