使用ruby将哈希保存到mysql记录中

时间:2012-07-12 01:33:19

标签: ruby-on-rails ruby

假设我有一个ruby哈希:

person={:name=>:Alex,:age=>10}

我希望我可以调用这样的API:

db.save :people, person

将在mysql数据库上执行以下SQL:

insert  nto people (name,age) values ('Alex',10)

这可以通过使用铁轨或其他红宝石来实现吗?

2 个答案:

答案 0 :(得分:1)

你可以调用ClassName.create!(your_hash),所以在你的场景中它看起来像这样:

Person.create!(person) # to create a record right away

person = Person.new(person) # to initialize the object first

person.save #  and then save it

无需使用任何外部gem,这是标准的ActiveRecord,Rails核心库之一。

答案 1 :(得分:0)

class Person<的ActiveRecord :: Base的 端

将Person类放在模型文件中。对应的表名应为人,其复数型号和首字母为小写。只需看看Rails的约定。

现在尝试

Person.create!(attributes).

属性就像列名对应的值。

例如

{:name => 'sandip'}  #here name is the column name and value is the 'sandip'