简体   繁体   English

Rails迁移,使用split添加新列-split()不起作用

[英]Rails migration, add new column using split - split() doesn't work

I'm trying to add a max and min column to my model, based on a delimited string from another column: 我正在尝试根据另一列中的定界字符串将max和min列添加到我的模型中:

804025|1356906|2246774

So the min should be: 804025 , and the max should be: 2246774 因此最小值应为: 804025 ,最大值应为: 2246774

I'm using this migration script: 我正在使用此迁移脚本:

def change
    add_column :mer14s, :rmax, :int
    add_column :mer14s, :rmin, :int
    Mer14.all.each do |mer|
        nums_a = []
        if mer.leading
            nums_a += mer.leading.split('|').map(&:to_i)
            puts mer.leading
            puts nums_a
        end
        if mer.lagging
            nums_a += mer.lagging.split('|').map(&:to_i)
        end
        if nums_a.length > 0
            mer.update_attributes(:rmax => nums_a.max)
            mer.update_attributes(:rmin => nums_a.min)
        end
    end
  end

However, the split('|') only returns the first element. 但是, split('|')仅返回第一个元素。

puts leading
puts num_a 

Output: 输出:

804025|1356906|2246774
804025

I've confirmed it works in the rails console by using: 我通过使用以下方法确认了它在rails console可以正常工作:

Mer14.all[18].leading.split('|').map(&:to_i)

Output [1189919, 3219748, 4010566] 输出 [1189919, 3219748, 4010566]

But it doesn't work in my migration file, nor does it work elsewhere (eg my models). 但是它不适用于我的迁移文件,也不适用于其他地方(例如,我的模型)。 Can anyone tell me why this is? 谁能告诉我为什么呢?

For some reason the split method didn't enjoy using a string inside rails. 出于某种原因, split方法不喜欢在rails中使用字符串。 Instead a regex was used, so the original: 而是使用了正则表达式,因此原始格式为:

nums_a += mer.leading.split('|').map(&:to_i)

Becomes: 变为:

nums_a += mer.leading.split(/\\|/).map(&:to_i)

This works for me: 这对我有用:

a = "804025|1356906|2246774"
a.split('|').map(&:to_i).max
=> 2246774
a.split('|').map(&:to_i).min
=> 804025

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM