>> Could you post actual error message and the code that generates
>> it? It
>> also couldn't hurt to post the relevant snippets from the
>> supplier_stock.rb and the migration.
>> --
>> Posted viahttp://www.ruby-forum.com/.
> Error occurs on the call to create:
> CODE:
> product = SupplierStock.find_by_productid(prodid)
> if product
> product.current_stock = s
> product.save
> else
> product = SupplierStock.create(
> :id => prodid,
> :current_stock => s
> )
> end
> ERROR:
> Exception encountered: RuntimeError: ERROR C23502 Mnull value in
> column "productid" violates not-null constraint FexecMain.c
> L1782 ExecConstraints: INSERT INTO supplier_stock
> ("yesterday_stock", "current_stock") VALUES(0, 0)
> SupplierStock Class:
I think you need to let ActiveRecord know where you're departing from
convention.
> class SupplierStock < ActiveRecord::Base
set_table_name "supplier_stock"
set_primary_key "productid"
> def self.table_name()
> "supplier_stock"
> end
> def self.primary_key()
> "productid"
> end
> end
> Table Schema:
> 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:
> "$1" FOREIGN KEY (productid) REFERENCES
> supplier_products(productid) ON DELETE CASCADE
You might also need to do the create step like:
unless prodid.nil?
if product = SupplierStock.find_by_id(prodid)
product.update_attribute(:current_stock, s)
else
product = SupplierStock.new do |ss|
ss.id = prodid
ss.current_stock = s
end
product.save
end
end
I don't think you can specify the :id on a create, but you can alter
the :id before the new record is saved. In your case, however, you
seem to have prodid.nil? to start and that can't be what you expect.
-Rob
Rob Biedenharn http://agileconsultingllc.com
R...@AgileConsultingLLC.com
Thanks for your help Rob. Here's what I'm sticking with:
if product = SupplierStock.find_by_productid(prodid)
product.update_attribute(:current_stock, s)
else
product = SupplierStock.new { |ss|
ss.id = prodid
ss.current_stock = s
}
product.save
end
Seems to work fine. But I still never learned why you can't specify
the id when you make a new ActiveRecord object. Here's a snipped from
my script/console with what I mean:
product = SupplierStock.new({:id => 600000, :current_stock => 3})
=> #<SupplierStock:0x6881cc8 @new_record=true,
@attributes={"yesterday_stock"=>0, "current_stock"=>3}>
### You can see that the ID is not included in @attributes above
product.id = 600000
=> 600000
product
=> #<SupplierStock:0x6881cc8 @new_record=true,
@attributes={"productid"=>600000, "yesterday_stock"=>0,
"current_stock"=>3}>
### But now that I specified it OUTSIDE the call to new, it is present.