使用值在Ruby中设置对象的键

时间:2012-02-27 21:10:33

标签: ruby-on-rails ruby

在循环中,我正在尝试将值设置为对象的键。不知道怎么做:

@user = {"username"=>"123", "full_name"=>"John Doe"}

@account = Account.new
@user.keys.each { |key|
  @account.key = @user[key]
}

返回错误:NoMethodError:undefined method`key ='

3 个答案:

答案 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”,对吗?

帐户是否有usernamefullname属性?它是否有key属性?它显然没有key,因为这就是你收到错误的原因。

如果帐户确实有usernamefullname,那么就这样做:

@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]")}