在循环中,我正在尝试将值设置为对象的键。不知道怎么做:
@user = {"username"=>"123", "full_name"=>"John Doe"}
@account = Account.new
@user.keys.each { |key|
@account.key = @user[key]
}
返回错误:NoMethodError:undefined method`key ='
答案 0 :(得分:3)
Ruby中的函数调用就像消息传递一样。所以你要找的是send。
示例中的@account
对象不是像@user
这样的哈希,而是一个Class实例。
但是Rails有一种更好的方法来初始化具有属性的模型:
@account = Account.new(username: '123', full_name: 'John Doe')
在Rails控制器中,如果您正确编写了表单,这些通常都在params
哈希:
@account = Account.new(params[:user])
如果您必须手动执行此操作,则可以:
@account = Account.new
# set all attributes at once
@account.attributes = @user
# this also works, but it's the least desirable
@user.each {|key, value| @account.send("#{key}=", value) }
最后一个示例有效,因为@account.key = value
实际上是方法调用的语法糖:@account.key=(value)
我强烈建议您阅读Rails Form Helpers,然后根据建议构建表单。
答案 1 :(得分:0)
看起来你想要的是将@ account.username设为123,将@ account.full_name设为“John Doe”,对吗?
帐户是否有username
和fullname
属性?它是否有key
属性?它显然没有key
,因为这就是你收到错误的原因。
如果帐户确实有username
和fullname
,那么就这样做:
@account.update_attributes!(@user)
如果没有,那我就不知道你要做什么了。
答案 2 :(得分:0)
这样做;
@user = {"username" => "123", "full_name" => "John Doe"}
@account = Account.new
@user.keys.each{|key| eval("@account.#{key} = @user[key]")}