2012-04-29 58 views
0

我正在尝试遍历从我的数据库中提取的食谱,解析每个配方中的成分并将成分插入到自己的表中。 的问题是,我不知道如何将我的内心选择当前成分变量: 目前,我发现了以下错误:ruby​​ on rails:如何在select语句中包含局部变量

ExtractIngredients.rb:21:在'查询':未知列'ing'in'field list'(Mysql :: Error)

请问如何在我的select语句中包含“ing”?

感谢, 李

begin 

db = Mysql.new 'localhost', 'root', 'pass', 'recs' 
results = db.query "SELECT id, freeText FROM recipes" 

nRows = results.num_rows 

for i in 0..nRows-1 
    curRow = results.fetch_row 
recipeInd = curRow[0] 
    recipeFreeText = curRow[1] 

    ingredients = getIngredients(recipeFreeText).to_s.scan(/\'(\w+)\'/).flatten 

    ingredients.each do |ing| 
      db = Mysql.new 'localhost', 'root', 'pass', 'recs' 

      # In the next awful select statement I'm trying to insert the current ingredient to the ingredient table if it isn't already there 
     db.query "INSERT INTO ingredient(name, created_at, updated_at) SELECT ing, created_at, updated_at FROM dummytable WHERE (SELECT count(*) FROM ingredient WHERE Name = ing)=0" 

     ingInd = db.query "SELECT id FROM ingredient WHERE name=ing" 
      db.query "INSERT INTO ingredients_recipes(ingredient_id, recipe_id) ingInd, recipeInd" 
    end  
end 

end 
+0

你几乎从不想直接从Rails查询数据库。你为什么需要这样做? – Gareth

回答

1

使用字符串插值像任何其他Ruby字符串:#{ing}

也就是说,如果这是Rails的,你为什么做这样的事?并为每个成分创建一个新的MySQL?其中大部分都是在框架中进行的。

+0

thx :)我是新的铁轨,你能否给我一个简单的例子/参考正确的方式来做到这一点? (我只需要运行一次,所以我不想投入太多精力在里面) – user429400

+0

@ user429400如果只运行一次,那么它可能无所谓,但如果任何Rails的DB教程覆盖模型关系等 –

0

通过使用插值

"..... WHERE Name = '#{ing}' ...." 

如果您使用Rails,你为什么不使用模式,这种任务,而不是原始的SQL?