2017-06-29 28 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