如何更新rails中的数据

时间:2015-11-21 18:04:24

标签: ruby-on-rails ruby json

我有这个json数据,我想找到..如果' id'是可用的,然后不更新记录。

// Here is my json

{
    "service":
     [ {
        "id":4,
        "name": "1",
        "description": "Allkindofworks",
        "price": "200"
    },
    {
        "id":4,
        "name": "1",
        "description": "Allkindofworks",
        "price": "200"
    }]
}  

2 个答案:

答案 0 :(得分:2)

这应该有效,首先将其转换为哈希,

 return Promise.map(tagList, function(name){ // map is a bluebird utility
   return site.tags.findOne({name: name}).posts.sort('date', -1).limit(25).toArray();
 }).
 then(_.flatten). // flatten the list
 filter(function(item){ 
   return item.title !== title; // filter - also a bluebird utility, like Array#filter
 }).then(function(posts){
   return _.first(_.shuffle(posts), 5);
 });

然后您可以使用find_by_id循环并更新并尝试方法

result = {
    "service":
     [ {
        "id":4,
        "name": "1",
        "description": "Allkindofworks",
        "price": "200"
    },
    {
        "id":4,
        "name": "1",
        "description": "Allkindofworks",
        "price": "200"
    }]
}.to_hash

注意:我们使用result[:service].each do |s| Model.find_by_id(s[:id]).try(:update_attributes, {name: s[:name]}) end 的原因是为了防止记录未找到异常,如果找不到给定ID的记录,它将返回nil。并且find_by_id方法也只是尝试运行,如果发生任何问题,它不会抛出任何错误。

答案 1 :(得分:0)

如果我理解了你的问题,那么你将获得一些JSON数据,然后你想要更新experiment字段,如果你能找到它,否则就不管它了。只需利用id将您的JSON转换为json(我假设您将其作为字符串),如果找到它则更改字段,然后再将其更改回JSON。 / p>

看起来有点像这样:

Hash