0

我们正在尝试send strftime('%Y/%m/%d')在我们的 rails 3.2.12 应用程序中使用日期对象。这是我们在 中进行的测试rails console

irb(main):014:0> b=User.offset(1).first
  ←[1m←[35mUser Load (1.0ms)←[0m  SELECT "users".* FROM "users" LIMIT 1 OFFSET 1
=> #<User id: 2, login: "wsxl207", name: "?????", email: nil, encrypted_password: "55a48ac66ba164805d91dc5415455cd402e9c8b3a656620136a...", salt: "3ee
e529200bdcad3ed2f16a8749ede6f046130e2705714ab55d...", status: "active", user_type: "employee", input_by_id: 1, created_at: "2012-04-13 16:23:25", upda
ted_at: "2012-08-22 03:15:12">

irb(main):015:0> b.send('created_at').send("strftime('%Y/%m/%d')")
NoMethodError: undefined method `strftime('%Y/%m/%d')' for 2012-04-13 16:23:25 UTC:Time
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/activesupport-3.2.12/lib/active_support/time_with_zone.rb:332:in `method_missing'
        from (irb):15
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-3.2.12/lib/rails/commands/console.rb:47:in `start'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-3.2.12/lib/rails/commands/console.rb:8:in `start'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-3.2.12/lib/rails/commands.rb:41:in `<top (required)>'
        from script/rails:6:in `require'
        from script/rails:6:in `<main>'

irb(main):016:0> b.send('created_at').strftime('%Y/%m/%d')
=> "2012/04/13"

但是我们发现这send不适用于 strftime('%Y/%m/%d')with send("strftime('%Y/%m/%d')")。我们在这里缺少什么?谢谢您的帮助。

4

1 回答 1

2

send将方法名称(理想情况下作为符号,尽管字符串也可以)作为其第一个参数,并将方法调用的参数作为其余参数。所以我想你正在寻找的是:

b.send(:created_at).send(:strftime, "%Y/%m/%d")

也就是说,如果您在代码中明确执行此操作,您几乎肯定只想直接调用created_atand strftime,而不是使用元编程方法send

于 2013-04-07T00:51:48.380 回答