【问题标题】:How update a serialized column如何更新序列化列
【发布时间】:2017-06-29 12:44:36
【问题描述】:

有一个带有序列化列的大模型

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

【问题讨论】:

  • 试着把它分解成一个最小的问题。 city.places = ["school", "libary", "bank", "warehouse", "church"]; city.save city.errors。
  • 你序列化的列已经是一个数组,所以不需要使用split。在控制台试试这个:City.all.first.places.class,你会得到=> Array(顺便说一句,你可以跳过all直接去first)。
  • 而 city.places[1..-2].split(', ') 可能不会做你想做的事。更好的方法是去除所有空格的字符串(如果它们只能在逗号​​之后) city.places.gsub(/\s+/, "").split(',') 或只有空格在逗号之后 city.places.gsub(', ', ',').split(',')
  • @TomLord 消息是空的,base 是对象。 .
  • 让我们弄清楚...您的问题的一个最小的、可重现的例子是:puts city.places => <original>; city.places = <new>; city.save => true; city.places => <original> ???!!!!

标签: ruby-on-rails ruby serialization


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2013-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    • 2011-03-17
    • 2013-01-04
    • 1970-01-01
    相关资源
    最近更新 更多