在Rails模型中获取当前日期

5

我正在尝试在我的Rails模型中获取当前日期,代码如下:

在Photo.rb文件中:

  Paperclip.interpolates :prefix  do |attachment, style|
      :today_date => Date.today.to_s
      "#{:today_date}/#{attachment.instance.image_file_name}"
  end 

当我从客户端向服务器发送照片时,我收到一个错误,并在服务器上得到以下控制台输出。这告诉我存在“日期”函数的问题。
服务器控制台:
 Started POST "/photos.json" for 127.0.0.1 at 2013-02-20 13:47:35 -0800
 13:47:35 web.1  | 
 13:47:35 web.1  | SyntaxError 
             (/Users/AM/Documents/RailsWS/test/app/models/photo.rb:22: syntax 
               error, unexpected tASSOC, expecting keyword_end
 13:47:35 web.1  |      :today_date => Date.today.to_s
 13:47:35 web.1  |                    ^):
 13:47:35 web.1  |   app/controllers/photos_controller.rb:1:in `<top (required)>'

我做错了什么?我该如何将当前日期存入这个变量中?
谢谢。
2个回答

5

尝试:

Paperclip.interpolates :prefix  do |attachment, style|
  "#{Date.today.to_s}/#{attachment.instance.image_file_name}"
end 

3
如果你想要分配一个变量,你需要使用哈希语法。它应该长这样:

  Paperclip.interpolates :prefix  do |attachment, style|
      today_date = Date.today.to_s
      "#{today_date}/#{attachment.instance.image_file_name}"
  end 

我试过了。事实上,那是我尝试的第一件事情。但是它不起作用,所以我切换到上面写的版本。 - banditKing
2
只需去掉冒号即可。 "#{today_date}/#{attachment.instance.image_file_name}" - Andrei
现在rubocop建议使用Time.zone.today - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接