在Ruby on Rails上替换返回的活动记录哈希值

时间:2016-05-17 09:17:57

标签: ruby-on-rails ruby hash

我有一个hash on ruby​​ on rails active record method。

有一个名为'professional_type'的列,我希望使用'each'循环将其替换为另一个值。

但它没有用。

代码:

collection.each_with_index { |(key, value), index |

    if(key.professional_type == 'center_professional')

        key.professional_type = 'test' # does nothing
        key.professional_type << 'test' # this works and concats 'test' string to var

    end

}

这是 collection.inspect 结果:

[#<Professional id: 105, center_id: 20, name: "ABC", professional_type: "center_professional", created_at: "2014-05-28 12:21:48", updated_at: "2015-01-23 13:12:47", deleted_at: nil>, #<Professional id: 107, center_id: 20, name: "EDFG", professional_type: "center_professional", created_at: "2014-06-03 07:23:31", updated_at: "2015-01-23 13:15:35", deleted_at: nil>]

为什么如果我连接它将字符串添加到变量但是如果我分配一个新值它不起作用?我做错了什么?

谢谢大家。

2 个答案:

答案 0 :(得分:1)

这应该有效 -

collection.map { |key, value|

  if(value == 'center_professional')

    #concat key.professional_type + "<br>"
    collection[key] = 'test'
  end
}

答案 1 :(得分:1)

collection.collect do  |professional| 
    professional.professional_type = 'test' if(value == 'center_professional') 
    professional
end