lundi 11 janvier 2016

Rails build JSON object from hash and arrays via model

I am a beginner in ruby and rails and are trying to build a JSON result like this with ruby on rails:

{
    "blacklists": {
        "list1": [{
            "id": "123",
            "find": "foo",
            "type": "text"
        }],
        "list2": [{
            "id": "321",
            "find": "bar",
            "type": "text"
        }]
    }
}

I have been fooling around with this code for hours now and this is what I have come up with so far, but as you experienced programmers see it is not working.

@blacklist = {}
@bl = {}

key_category = KeywordCategory.where("global_list = ? OR unit_id = ?",1,1)

key_category.each do |kc|

kc.keywords.each do |kw|
 @keywords = {}
 @keywords['id'] = kw.id
 @keywords['find'] = kw.data
 @keywords['type'] = kw.is_regexp ? "regexp" : "text"
 @bl.merge!(@keywords)
end

end

@blacklist['blacklist'] = @bl

return @blacklist.to_json

I cannot tell you how much I would appreciate help with this one!

Aucun commentaire:

Enregistrer un commentaire