我想在rails函数中编写一个ruby函数,它将为任何模型创建一个新对象。这是我到目前为止的内容Ruby on Rails:将属性值分配到泛型模型
def create_populated_object(model)
test_object = model.new
model.columns.each do |column|
attr_name = column.name
attr_type = column.type
#test_object.assign_attributes(attr_name+':'+ "9")
puts "#{':'+attr_name} => #{attr_type}"
if attr_type.to_s == 'integer'
b = '{:' + attr_name.to_s + '=>' + 9.to_s + '}'
puts b
test_object.assign_attributes(b)
puts "it worked"
elsif attr_type.to_s == 'string'
puts "string"
elsif attr_type.to_s == 'datetime'
puts "date time"
elsif attr_type.to_s == 'boolean'
puts "boolean"
elsif attr_type.to_s == 'text'
puts "text"
else
puts "UNKNOWN ATTRIBUTE TYPE"
end
end
puts test_object
end
在我的示例中,id是模型的第一个属性。我尝试了价值9分配给它,但我不断收到此错误:
NoMethodError:未定义的方法`stringify_keys'为‘{:ID => 9}’:字符串
任何人都知道如何解决这一问题?
总是让一切都涉及到这个问题的一个小例子。在这里,分配的代码和数据库状态以及其他任何解释“我尝试给它赋值9”。阅读帮助重新问好问题。 (即使事实证明,在这个特定的问题中有足够的解决方案。) – philipxy