Rails 通过模型从散列和数组构建 JSON 对象

Rails build JSON object from hash and arrays via model

我正在尝试 post 数据到 API,API 正在请求一个 JSON 请求,因为这个 :

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

我的问题是用代表上述内容的散列和数组构建一个 JSON。

这是我目前的代码:

@blacklist = {}
@bl = {}

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

key_category.each do |kc|

bl_name = kc.name # <- "list1, list2 etc."

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

这段代码给了我这个 JSON(与 API 想要的有点不同):

{
"blacklists":
{"id":123,
"find":"foo",
"type":"text"
}
}

如何更改我的代码,使其根据顶部 JSON 显示?

尝试这样的事情:

@blacklist = {}
@bl = {}

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

key_category.each do |kc|

  tmparray = []

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

@blacklist['blacklist'] = @bl

return @blacklist.to_json