Ruby / Rails迭代数组并保存到db?

时间:2014-07-24 16:17:26

标签: ruby-on-rails

我想将@enc中的每个字符串作为值

放入column_name的每个字段中
@enc=["hUt7ocoih//kFpgEizBowBAdxqqbGV1jkKVipVJwJnPGoPtTN16ZAJvW9tsi\n3inn\n", "wGNyaoEZ09jSg+/IclWFGAXzwz5lXLxJTUKqCFIiOy3ZXRgdwFUsNf/75R2V\nZm83\n", "MPq3KSzDzLvTeYh+h00HD+5FAgKoNksykJhzROVZWbIJ36WNoBgkSoicJ5wx\nog0g\n"]


Model.all.each do |row|
encrypted = @enc.map { |i| i}
row.column_name = encrypted
row.save!
end

我的代码将数组@enc中的所有字符串放入一个字段中? 我不要那个。

帮助

3 个答案:

答案 0 :(得分:0)

我认为你正在寻找这样的东西:

@enc.each do |str|
  m = Model.new
  m.column_name = str
  m.save
end

答案 1 :(得分:0)

默认情况下,Rails不允许进行质量分配。您必须将所允许的参数列入白名单。您是否尝试过以下类似的事情?

@enc.each do |s|
   cparams = create_params 
   cparams[:column_name] = s
   Model.create(cparams)
end


def create_params
   params.permit(:column_name)
end

答案 2 :(得分:0)

您需要指定要保存的列名称。通过单独设置每个列,您还可以避免质量分配错误:

@enc=["hUt7ocoih//kFpgEizBowBAdxqqbGV1jkKVipVJwJnPGoPtTN16ZAJvW9tsi\n3inn\n", "wGNyaoEZ09jSg+/IclWFGAXzwz5lXLxJTUKqCFIiOy3ZXRgdwFUsNf/75R2V\nZm83\n", "MPq3KSzDzLvTeYh+h00HD+5FAgKoNksykJhzROVZWbIJ36WNoBgkSoicJ5wx\nog0g\n"]

model = Widget.new
column_names = [:column1, :column2, :column3]

@enc.each_with_index do |s, i|
  model[column_names[i]] = s
end

model.save