在一个循环内,我试图将该值设置为对象的键值。不知道如何做到这一点:使用一个值在Ruby中设置一个对象的键值
@user = {"username"=>"123", "full_name"=>"John Doe"}
@account = Account.new
@user.keys.each { |key|
@account.key = @user[key]
}
返回的错误:NoMethodError:未定义的方法`键=”
在一个循环内,我试图将该值设置为对象的键值。不知道如何做到这一点:使用一个值在Ruby中设置一个对象的键值
@user = {"username"=>"123", "full_name"=>"John Doe"}
@account = Account.new
@user.keys.each { |key|
@account.key = @user[key]
}
返回的错误:NoMethodError:未定义的方法`键=”
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) }
最后EXA因为@account.key = value
实际上是一个方法调用的语法糖:@account.key=(value)
我强烈建议通过Rails Form Helpers阅读和建立你的表格如何建议。
它看起来像你想要的是让@ account.username是123,和@ account.full_name是“John Doe”,对吗?
帐户是否有username
和fullname
属性?它有key
属性吗?它显然没有key
,因为这就是你得到这个错误的原因。
如果账户确实有username
和fullname
,然后就去做:
@account.update_attributes!(@user)
如果没有的话,我不知道你想做什么。
这样做;
@user = {"username" => "123", "full_name" => "John Doe"}
@account = Account.new
@user.keys.each{|key| eval("@account.#{key} = @user[key]")}
谢谢亚当,更新后的例子为我工作。真棒。 – oprogfrogo 2012-02-27 21:31:24