Inside a loop, I’m trying to set the value as the object’s key. Not sure how to do this:
@user = {"username"=>"123", "full_name"=>"John Doe"}
@account = Account.new
@user.keys.each { |key|
@account.key = @user[key]
}
That returns an error of: NoMethodError: undefined method `key=’
Function calls in Ruby act like message-passing. So what you are looking for is send.
The
@accountobject in your example is not a Hash like@user, it is a Class instance.But Rails has an even better way to initialize a Model with attributes:
In a Rails controller, these are usually in the
paramshash if you wrote your form correctly:If you must do it manually, you can:
The last example works because
@account.key = valueis actually syntactic sugar for a method call:@account.key=(value)I highly recommend reading through Rails Form Helpers and building your forms how it suggests.