如何在不替换变量的情况下在 table 中插入数据?

How to insert data in the table without substituting the variable?

我有一个创建很多项目的 rake 文件。

namespace :db do
  namespace :seed do
    desc "items table"
      task :items=> :environment do
        Item.create(name: "first_name", process: "clean the item #{test} then pack and send to #{location}")
        ................................................
      end
  end
end

当我执行 rake db:seed:items 时,我无法在不替换变量的情况下将此数据插入 table。有没有办法在没有变量替换的情况下插入此数据,以便我以后可以替换变量?

如果您想将插值推迟到以后的时间并仍然使用 Ruby 字符串插值表示法,您可以这样做:

string = 'clean the item #{test} then pack and send to #{location}'
values = {
  test: "paperclip",
  location: "head office"
}

string.gsub(/\#\{([^}]+)\}/) do
  values[.to_sym]
end

# => "clean the item paperclip then pack and send to head office"

您甚至可以将其包装成一个简单的方法:

def interpolate(string, values)
  string.gsub(/\#\{([^}]+)\}/) do
    values[.to_sym]
  end
end

其中,如果你想有点大胆,你可以修补成字符串:

class String
  def interpolate(values)
    self.gsub(/\#\{([^}]+)\}/) do
      values[.to_sym]
    end
  end
end

请注意,这只会对 #{x} 而不是 #{x.method_call}#{x+1} 甚至 #{x[y]} 进行最基本的插值。为此,您可能需要使用更随意的代码评估方法,但这条路充满了危险。