2017-06-29 46 views
0

有一个与序列化列如何更新连载列

serialize :places 

一个大模型,存储了好几个地方。

City.all.first.places 
=> "[school, libary, store, flowers, bank]" 

我想删除所有鲜花,并重新命名“商店”到“仓库”
如果有一个“店”,应该也是一个“教会”

我创建了下面的任务,但如果我检查一些条目,数据是相同的。

City.all.each do |city| 
    next unless city.places.present? 
    places = city.places[1..-2].split(', ') 
    places.delete('flowers') 
    if places.include?('store') 
    places.delete('store') 
    places.push('warehouse','church') 
    end 
    city.places = places 
    city.save 
end 
+2

尝试将此分解为*最小*问题。 'city.places = [“school”,“libary”,“bank”,“warehouse”,“church”]; city.save' < - 这是否失败?为什么?检查'city.errors'。 –

+0

您序列化的列已经是一个数组了,所以不需要使用'split'。在控制台中试试这个:'City.all.first.places.class',你会得到'=> Array'(顺便说一句,你可以跳过'all'并直接进入'first')。 – Gerry

+0

和city.places [1 ..- 2] .split(',')不可能做你想做的事。更好的方法是去除所有空白字符串(如果它们只能在逗号​​后面出现)city.places.gsub(/ \ s + /,“”).split(',')或者只有空白字符串在像city.places.gsub(',',',')之类的逗号之后。split(',') –

回答

0

这听起来像你应该有地方是它自己的表,然后有一个连接表将它们连接到城市,如:

class City < ApplicationRecord 
    has_many :city_places 
    has_many :places, through: :city_places 
end 

class CityPlace < ApplicationRecord 
    belongs_to :city 
    belongs_to :place 
end 

class Places < ApplicationRecord 
    has_many :city_places 
    has_many :cities, through: :city_places 
end 

城市这样可以有很多的地方,如果你想重命名一个地方,你可以在数据库中改变它的名字。这里是the docs for this kind of relationship in rails