我们正在尝试将send
strftime('%Y/%m/%d')
与rails 3.2.12 app中的日期对象一起使用。以下是我们在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')
send("strftime('%Y/%m/%d')")
不兼容。我们在这里缺少什么?谢谢你的帮助。
答案 0 :(得分:2)
send
将方法名称(理想情况下为符号,尽管字符串也起作用)作为其第一个参数,并将方法调用的参数作为其余参数。所以我想你正在寻找的是:
b.send(:created_at).send(:strftime, "%Y/%m/%d")
也就是说,如果您在代码中明确地这样做,那么您几乎肯定希望直接调用created_at
和strftime
,而不是使用元编程方法send
。< / p>