如何使用PG gem插入Postgres表

时间:2017-02-28 16:52:51

标签: ruby postgresql pg

我用Postgres创建了三个数据库模式。表格肯定在那里,我使用\dt的shell来查看它们。

尝试使用seeds.rb文件进行INSERT时,我的SqlRunner失败了。终端在" 11.18"或附近返回PG :: SyntaxError。前一行也是一个浮点数,所以我不知道什么是错的。

模型如下:

require('pg')
require('../project_giclee_db/sql_runner')


class Material

  attr_reader :id, :product_name, :guk_name, :roll_width_in,  :roll_length_metres, :list_price, :cost_per_sqm,
    :cost_per_sqm_with_ink, :factor_n, :sell_per_sqm, :rounded_sale_price


  def initialize( options )
    @id = options['id'].to_i
    @product_name = options['product_name']
    @guk_name = options['guk_name']
    @roll_width_in = options['roll_width_in'].to_i
    @roll_length_metres = options['roll_length_metres'].to_i
    @list_price = options['list_price'].to_f
    @cost_per_sqm = options['cost_per_sqm'].to_f
    @cost_per_sqm_with_ink = options['cost_per_sqm_with_ink'].to_f
    @factor_n = options['factor_n'].to_f
    @sell_per_sqm = options['sell_per_sqm'].to_f
    @rounded_sale_price = options['rounded_sale_price'].to_i

  end


  def save
    sql = "INSERT INTO materials (product_name, guk_name, roll_width_in, roll_length_metres,
    list_price, cost_per_sqm, cost_per_sqm_with_ink, factor_n, sell_per_sqm, rounded_sale_price)
    VALUES (#{@product_name}, #{@guk_name}, #{@roll_width_in}, #{@roll_length_metres}, #{@list_price}
    #{@cost_per_sqm}, #{@cost_per_sqm_with_ink}, #{@factor_n}, #{@sell_per_sqm}, #{@rounded_sale_price}
    ) RETURNING *"

    data = SqlRunner.run(sql).first
    @id = data['id']
  end


  def self.delete_all
    sql = "DELETE FROM materials"
    SqlRunner.run(sql)
  end

end

Runner看起来像:

require('pg')

class SqlRunner

  def self.run(sql)
    begin
   db = PG.connect( {dbname: 'giclee_db', host: 'localhost'} )
     result = db.exec(sql)
    ensure
    db.close
  end
   return result
 end

end

种子数据如下:

require('../models/materials')
require('pry-byebug')

Material.delete_all

 @material1 = Material.new( { 'product_name' => 'giclee_canvas',   'guk_name' => 'canvas',
'roll_width_in' => 44, 'roll_length_metres' => 12, 'list_price' => 150.00,
'cost_per_sqm' => 11.18, 'cost_per_sqm_with_ink' => 14.18, 'factor_n' => 11.00,
'sell_per_sqm' => 156.03, 'rounded_sale_price' => 156
} )


@material1.save

2 个答案:

答案 0 :(得分:1)

你的字符串应该有引号:

def save
 sql = "INSERT INTO materials (product_name, guk_name, roll_width_in, roll_length_metres,
list_price, cost_per_sqm, cost_per_sqm_with_ink, factor_n, sell_per_sqm, rounded_sale_price)
VALUES ('#{@product_name}', '#{@guk_name}', #{@roll_width_in}, #{@roll_length_metres}, #{@list_price}
#{@cost_per_sqm}, #{@cost_per_sqm_with_ink}, #{@factor_n}, #{@sell_per_sqm}, #{@rounded_sale_price}
) RETURNING *"

  data = SqlRunner.run(sql).first
  @id = data['id']
end

答案 1 :(得分:0)

问题是SQL中的行末尾缺少逗号:

VALUES ('#{@product_name}', '#{@guk_name}', #{@roll_width_in}, #{@roll_length_metres}, #{@list_price}