gpt4 book ai didi

ruby-on-rails - 无法在 Rails 3.2.14、Ruby 2.1.0 的事件记录中添加键、值对

转载 作者:太空宇宙 更新时间:2023-11-03 16:18:07 25 4
gpt4 key购买 nike

最近我将我的 Rails 应用程序使用的 ruby​​ 版本从 1.9 升级到 2.1.0。以前下面的代码用于工作:

# in Ruby 1.9
user = User.first
# then adding my own field to it
user[:phone_no] = "+91 0000 888 773"

# but now in Ruby 2.1.0,
user[:phone_no] = "+91 0000 888 773"

上面的一段代码抛出了这个错误。

 NoMethodError: undefined method `call' for :warn:Symbol
from /home/xyz/.rvm/gems/ruby-2.1.0/gems/activesupport-3.2.14/lib/active_support/deprecation/reporting.rb:13:in `block (2 levels) in warn'
from /home/xyz/.rvm/gems/ruby-2.1.0/gems/activesupport-3.2.14/lib/active_support/deprecation/reporting.rb:13:in `each'
from /home/xyz/.rvm/gems/ruby-2.1.0/gems/activesupport-3.2.14/lib/active_support/deprecation/reporting.rb:13:in `block in warn'
from /home/xyz/.rvm/gems/ruby-2.1.0/gems/activesupport-3.2.14/lib/active_support/deprecation/reporting.rb:12:in `tap'
from /home/xyz/.rvm/gems/ruby-2.1.0/gems/activesupport-3.2.14/lib/active_support/deprecation/reporting.rb:12:in `warn'
from /home/xyz/.rvm/gems/ruby-2.1.0/gems/activerecord-3.2.14/lib/active_record/attribute_methods/write.rb:32:in `write_attribute'
from /home/xyz/.rvm/gems/ruby-2.1.0/gems/activerecord-3.2.14/lib/active_record/attribute_methods/dirty.rb:67:in `write_attribute'
from /home/xyz/.rvm/gems/ruby-2.1.0/gems/activerecord-3.2.14/lib/active_record/attribute_methods.rb:31:in `[]='
from (irb):3
from /home/xyz/.rvm/gems/ruby-2.1.0/gems/railties-3.2.14/lib/rails/commands/console.rb:47:in `start'
from /home/xyz/.rvm/gems/ruby-2.1.0/gems/railties-3.2.14/lib/rails/commands/console.rb:8:in `start'
from /home/xyz/.rvm/gems/ruby-2.1.0/gems/railties-3.2.14/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'

为了解决这个问题,我正在创建一个新的散列,然后向其中添加其他字段。

new_user = {}
new_user[:address] = user.address
new_user[:first_name] = user.first_name
new_user[:last_name] = user.last_name

我无法理解为什么以前的代码在 Ruby 2.1.0 中不起作用。在不同场景的许多地方升级 ruby 后,我一直遇到这个问题,例如在渲染模板时。

# in Ruby 1.9, this used to work and not in Ruby 2.0
render :template=>"share/index.html.erb"
# in Ruby 2.0, the below code works
render :template=>"share/index"

我不知道 Ruby 2.0 中发生了什么变化导致了所有这些错误。

最佳答案

首先获取用户记录如下图:

@user_list = User.select("address,first_name, last_name")

之后,您可以使用 merge 合并任何属性!如下图:

render :json => @user_list.as_json.map{|x|x.merge!("phone"=>"123456789")}

关于ruby-on-rails - 无法在 Rails 3.2.14、Ruby 2.1.0 的事件记录中添加键、值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39383596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com