Trouble with IDs

Hello,

I am getting strange results with the following code:

def self.process_product(supplier_productid)
local_product = Product.find(:first, :conditions => [“supplierid =
9 and supplier_productid = :id”, {:id => supplier_productid}])

if local_product
  local_product.update_attributes(attributes)

  begin
    supplier_stock = SupplierStock.find(local_product.productid)
  rescue Exception => e
    puts e.to_s
    supplier_stock = SupplierStock.new(
      :id => local_product.productid,
      :yesterday_stock => stock || -999,
      :current_stock => stock || -999
    )

supplier_stock[:productid] = local_product.productid

    supplier_stock.save
  else
    supplier_stock.yesterday_stock = supplier_stock.current_stock
    supplier_stock.current_stock = stock
    supplier_stock.save
  end
else
  ...

The database information:
###################################

db=# \d supplier_stock
Table “public.supplier_stock”
Column | Type | Modifiers
-----------------±--------±-------------------
productid | integer | not null
current_stock | integer | not null default 0
yesterday_stock | integer | not null default 0
Indexes:
“supplier_stock_pkey” primary key, btree (productid)
Foreign-key constraints:
“supplier_stock_productid_fkey” FOREIGN KEY (productid) REFERENCES
supplier_products(productid) ON DELETE CASCADE

db=# select * from supplier_products_productid_seq;
sequence_name | last_value | increment_by |
max_value | min_value | cache_value | log_cnt | is_cycled |
is_called
---------------------------------±-----------±-------------
±--------------------±----------±------------±--------±----------
±----------
supplier_products_productid_seq | 464931 | 1 |
9223372036854775807 | 1 | 1 | 32 | f |
t
(1 row)

###################################

And the error (occurs on the first call to save, in the exception
handling code):

RuntimeError: ERROR C23502 Mnull value in column “productid”
violates not-null constraint FexecMain.c L1782
RExecConstraints: INSERT INTO supplier_stock (“yesterday_stock”,
“current_stock”) VALUES(-999, -999)

From my understanding of Rails, when I insert to the supplier_stock
table, the primary key (defined as productid in the database table and
the class both) should be determined automatically whether I
define :id in the SupplierStock object’s new method or not. You will
notice I have commented one line of code. Uncommenting that line
eliminates the error. Why is it when I explicitly specify :productid
outside the new method that it works? Additionally, when I create the
SupplierStock object, if I immediately print out the keys and values
after the object is created, :id is not defined at all. Any insights?
Thanks.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs