Forum: Ruby on Rails association not inserted automatically.

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Satya (Guest)
on 2006-02-16 06:03

   I am trying to write a sample application.

I have

class LineItem< ActiveRecord::Base
belongs_to : order


class Order < ActiveRecord::Base
has_one :line_item

Now in the controller i am trying :

def add

@ord =[:ord])
@ord.line_item =[:lineitem])
redirect_to :action => 'list'
render :action => 'new'


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 (Guest)
on 2006-02-16 06:11
pleaase ?
Kent S. (Guest)
on 2006-02-16 06:23
(Received via mailing list)
Don't you think that your order should have many LineItems? Like

class Order < AR::Base
  has_many :line_items

class LineItem < AR::Base
  belongs_to :order


order = @params[:order]
li = @params[:line_item]

order.line_items << li!!

Satya (Guest)
on 2006-02-16 06:27
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
Satya (Guest)
on 2006-02-16 07:00
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.

Kent S. (Guest)
on 2006-02-16 07:05
(Received via mailing list)
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?

Satya (Guest)
on 2006-02-16 07:33
unfortunately my log file is not associated... theres some error with
that.. i have to fix that tooo :(
Satya (Guest)
on 2006-02-16 07:38
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
belongs_to Order

can i also say

belongs_to Order via orders_id ?
Kent S. (Guest)
on 2006-02-16 07:45
(Received via mailing list)
On 2/16/06, Satya <removed_email_address@domain.invalid> wrote:
> well... well....
> can i also say
> LineItem
> belongs_to Order via orders_id ?


class LineItem < AR::Base
  belongs_to :order, :foreign_key => 'orders_id'

Satya (Guest)
on 2006-02-16 07:48
Thanks man... Appreciate your help.
This topic is locked and can not be replied to.