satya
February 16, 2006, 5:03am
1
Hello,
I am trying to write a sample application.
I have
class LineItem< ActiveRecord::Base
belongs_to : order
end
&&
class Order < ActiveRecord::Base
has_one :line_item
end
Now in the controller i am trying :
def add
@ord = Order.new(params[:ord])
@ord.line_item = LineItem.new(params[:lineitem])
if @ord.save
redirect_to :action => ‘list’
else
render :action => ‘new’
end
end
and that is giving an exception saying foreign key constraint fails on
line_item because the order_id is 0 and more over the order is not saved
!
any help ?
satya
February 16, 2006, 5:23am
3
Don’t you think that your order should have many LineItems? Like
class Order < AR::Base
has_many :line_items
end
class LineItem < AR::Base
belongs_to :order
end
now
order = Order.new @params [:order]
li = LineItem.new @params [:line_item]
order.line_items << li
order.save!
li.save!
–
Kent
satya
February 16, 2006, 5:27am
4
order and line_items are just names that i was using… i was actually
trying the basics with dealing records on ruby.
i was trying one-one relationship.
and that didnt work !
why was i getting that foreign-key constraint error ?
Wont ruby insert the order and line_item when i do a @ord.save ?
satya
February 16, 2006, 6:05am
5
Hm, I’ve just created the same models as you are using and them work
as expected.
Strange, really. Can you check what sql statements get executed in
your log file?
Kent
satya
February 16, 2006, 6:33am
6
unfortunately my log file is not associated… theres some error with
that… i have to fix that tooo
satya
February 16, 2006, 6:38am
7
well… well…
its a typo that was causing this error… foreign key constraint fails
!!
in the line_item table i had a orders_id column instead of order_id…
i changed that and it worked fine just like yours !!
I wonder how one could fix that…
Is there a way that i can tell ruby , dont use your imagination, just
work as told ?
I mean, just like i say
LineItem
belongs_to Order
can i also say
LineItem
belongs_to Order via orders_id ?
satya
February 16, 2006, 6:45am
8
On 2/16/06, Satya [email protected] wrote:
well… well…
can i also say
LineItem
belongs_to Order via orders_id ?
Yes.
class LineItem < AR::Base
belongs_to :order, :foreign_key => ‘orders_id’
end
Kent
satya
February 16, 2006, 6:48am
9
Thanks man… Appreciate your help.
satya
February 16, 2006, 6:00am
10
its a simple question :
when order is saved would line_item be saved or should i save them
seperately ?
if they are supposed to be save automatically can someone tell me how ?
assuming @ord contains the order.
@line_item contains the line_item.
Thanks