I'm using Rails Edge.
----
class PayjunctionOrder < ActiveRecord::Base
has_many :line_items
end
------------------
----
class LineItem < ActiveRecord::Base
belongs_to :order,
:class_name => "PayjunctionOrder",
:foreign_key => "order_id"
...
------------------
----
class StoreController < ApplicationController
def checkout_complete
...
@order = PayjunctionOrder.new
@order.line_items << LineItem.new(:product => product, :quantity =>
qty, :total_price => product.price * qty)
@order.save!
...
------------------
When I try to save, I get:
Mysql::Error: #23000Column 'order_id' cannot be null: INSERT INTO
line_items (`order_id`, `total_price`, `product_id`, `quantity`)
VALUES(NULL, '285.0', 5, 1)
The development.log shows the insert being done for the
PayjunctionOrder, but the inserts for the children fail on this NOT
NULL constraint. So for whatever reason, order_id isn't being set in
the children.
What's weird is that it will work just fine (as advertised) by renaming
the column "order_id" to "payjunction_order_id" in the line_items table
and doing this instead:
----
class LineItem < ActiveRecord::Base
belongs_to :payjunction_order
...
------------------
However, this isn't an optimal solution.
So it seems like maybe Rails is ignoring the :class_name and
:foreign_key options in belongs_to. Does anyone have any insight as to
whats going on here? Thanks for the help.
create_table "line_items", :force => true do |t|
t.column "product_id", :integer,
:default => 0, :null => false
t.column "order_id", :integer,
:default => 0, :null => false
t.column "quantity", :integer,
:default => 0, :null => false
t.column "total_price", :decimal, :precision => 8, :scale => 2,
:default => 0.0, :null => false
end
create_table "payjunction_orders", :force => true do |t|
t.column "total_amount", :decimal, :precision => 8, :scale =>
2, :default => 0.0, :null => false
t.column "response_code", :string, :limit => 5, :default => "",
:null => false
t.column "response_message", :string
t.column "tracking_code", :string, :limit => 15
t.column "cc_last_four", :string, :limit => 22
t.column "first_name", :string, :limit => 30
t.column "last_name", :string, :limit => 20
t.column "email", :string, :limit => 30
end
Seems that the parent class also needs to know what the foreign key is
called in the child. So, you'd need the following:
----
class PayjunctionOrder < ActiveRecord::Base
has_many :line_items, :foreign_key => "order_id"
end
------------------
I guess it makes sense, but it seems kinda redundant to me. Also, it's
not explicitly mentioned in the docs from what I could see; I really
think it needs to be. Nudge-nudge to the Rails Gods.