Rails 3 - How to Create a JSON Object to store in the database

后端 未结 3 605
隐瞒了意图╮
隐瞒了意图╮ 2021-01-30 07:33

I\'m creating an AuditLog observer that watches over several models.

I\'d like the observer to have an after_create, which creates a JSON object that is stored in a data

3条回答
  •  暖寄归人
    2021-01-30 07:57

    First, definitely check out ActiveRecord serialize and see if it does what you need: http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-serialize

    However, if you need JSON specifically (serialize uses YAML by default), then you can always fake it by hand.

    You can simply build a hash in Ruby and then call to_json on it before assigning it to your model attribute.

    data = { 'photoid' => 123, 'photoname' => "asdasd", 'creator_id' => "asdasd" }
    myrecord.stored_data = data.to_json
    myrecord.save
    

提交回复
热议问题