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 database column. It will contain data like {photoid:123, photoname: "asdasd", creator_id: "asdasd"} etc...
In Rails, how do I create this type of JSON object and then how do I insert it into the DB along with other non-JSON fields?
Thanks
Click the Add button and select Column. On the Column element, specify values for the Index and Value attributes. Click the Add button in the sub-menu and select Add Same. Repeat the last two steps to add additional columns and elements from the JSON file.
We use OPENJSON() function for converting the JSON output from a variable into a tabular format. We get the output in different rows and columns, and later, it can be inserted into SQL Server tables. In this output, we can see the following columns: Key: We can consider it as a row number in a table.
SQL Server and Azure SQL Database have native JSON functions that enable you to parse JSON documents using standard SQL language. You can store JSON documents in SQL Server or SQL Database and query JSON data as in a NoSQL database.
Current versions of rails support json serialisation out of the box. Define your field as a string (or text) in the migration and then:
class Foo < ActiveRecord::Base serialize :field, JSON end bar = Foo.new bar.field = [1,2,3] bar.save
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With