Rails: Reconstructing ActiveRecord Objects from a JSON array - ruby-on-rails

I have a JSON array with ActiveRecord objects. These objects can be reconstructed using the from_json method, which every AR object has. However with from_json it's only possible to reconstruct one single object.
To process an array, I could of course just extract substrings from the JSON array and create every object from it's own substring in a loop or so. However I'm wondering if there is a better way to do this, without string manipulation involved.

I would do
sudo gem install json
After that just
require "json"
and do
JSON.load(array_of_ar_json_representation)
or
JSON.parse(array_of_ar_json_representation)
what fits better for you.
Both of these methods return Ruby data structure that corresponds to the json structure. So, if you have a json array of obejcts, after JSON.load or JSON.parse you'll get Ruby array of hashes. You should't have any problems to manipulate this kind of structure.

Related

Dealing with single value hash or multiple value array in JSON data

I have a JSON data feed where the value is a hash if single value and is an array if there are multiple values (see JSON data below).
JSON data:
# multiple values in option
{"options":{"option":[{"$t":"hasShots"},{"$t":"housebroken"}]}
# single value in option
{"options":{"option":{"$t":"hasShots"}}
I can do a check to see if the value is a hash or array using is_a? in Ruby, then extract the data accordingly and convert it to an object. Is this how it would typically be done or is there a better, more elegant way to code it in Ruby?
(NB: I figure this is such a common thing that there might be good solution to handling it. I google but it kept giving me how to parse JSON data's and creating JSON in Rails.)
I can do a check using is_a?. Is this how it would typically be done?
That's how I would do it! I think the more common scenario is for the JSON (or whatever) to have a consistent design, and have the objects in an array even if there's just one.

What's the best way to allow users to input fields that will be serialized as hashes or arrays?

I have a field that is stored like this:
serialize :value
And, I'd like to store it as an array/hash/string depending on the input format. Is there an accepted best practice about how to handle this? The input will always come from the user.
If I understand your problem correctly, you are talking about the opposite of serialization, which is parsing or tokenzing (converting a string into meaningful pieces)... That's a very generic problem, but take a look at the String.match and String.scan to get you started. Here are some stack overflow quetions that could be helpful (remember to search for things like this first!)
What's the "ruby way" to parse a string for a single key/value?
How do I tokenize this string in Ruby?
The best practice is to serialize Arrays and Hashes. When it comes to string there is no need for serialization. HTML form elements like checkboxes posts the array, which you can be serialized and saved directly in table. For Hashes, you should manipulate yourself accordingly and apply to the attribute.

How can I get the count of hash keys that match an array in MongoDB?

I am using mongoid for rails (latest version).
I have a collection full of documents, each with a property that is a hash.
I want to do a query that will determine how many elements of a given array are hash keys in the array in a single document.
Something like:
#count = Product.where('id':'343434343').vendors_in_array('Walmart','Kmart').count()
Is this possible or do I need to pull back the entire document and figure it out in RoR?
I will handle this in some other way because it doesn't seem to be the best approach.

controlling sort order of json output in Ruby on Rails (Ruby 1.8)

Is there any way to convert a ruby array/hash structure to JSON AND specify the output order of the elements?
Having the actually order of the elements vary is not functionally important, BUT it just makes debugging tough... It would be nicer if I could somehow specify the tag order to the json output, so the human reading the json can easily find the tag they are looking for.
No browsers do not guarantee sort order of objects. If you need sort order you need to use an indexed array.

Convert XML into a Dataset

I'm trying to convert an XML document into a dataset that I can import into a database (like SQLite or MySQL) that I can query from.
It's an XML file that holds most of the stuff in attributes. This is part of a Rails project so I'm very inclined to use Ruby (and that's the language I'm most comfortable with at the moment).
I'm not sure how to go about doing that and I'd welcome both high-level and low-level contributions.
xmlsimple can convert your xml into a Ruby object (or nested object) which you can then look over and do whatever you like with. Makes working XML in Ruby really easy. As Jim says though depends on your XML complexity and your needs.
There are three basic approaches:
Use ruby's xml stream parsing facilities to process the data with ruby code and write the appropriate rows to the database.
Transform the xml using xslt to a non-XML stream format and feed that into a ruby program that updates the database
Transform the xml with xslt into a format acceptable to the bulk-loading tool for whatever database you are using.
Only you can determine the best approach depending on the XML schema complexity and the type of mapping you have to perform to get it into relational format.
It might help if you could post a sample of the XML and the DB schema you have to populate.
Will it load model data? If you're on *nix take a look at libxml-ruby. =)
With it you can load the XML, and iteration through the nodes you can create your AR objects.
You can have a look at the XMLMapping gem. It lets you define different classes depending upon the structure of your XML. Now you can create objects from those classes.
Now you will have to write some module which actually converts these XMLMapping objects into ActiveRecord objects. Once those are converted to AR objects you can simply call save to save those objects into the corresponding tables.
It is a long solution but it will let you create objects out of your XML without iterating over it. XMLMapping will do it for you.
Have you considered loading the data into an XML database?
Without knowing what the structure of the data is, I have no idea what the benefits of an RDBMS over an XML DB are.

Resources