rails has_and_belongs_to_many problem

I

Igor Anic

I have two classes Album and Korisnik (think about that as user),
they are connected with album_korisnik table (I have pluralization
turned off).

Her is the declaration:

class Album < ActiveRecord::Base
...
has_and_belongs_to_many :prijatelji, :class_name => 'Korisnik'
...

class Korisnik < ActiveRecord::Base
...
has_and_belongs_to_many :albumi_prijatelja, :class_name => 'Album'
...


I'm trying to add new korisnik to the album, and this is not working:
prijatelji << k
but this line is working ok
k.albumi_prijatelja << self

In the first case i don't get any error in the log, and don't get any
sql commands in transaction.

What I'm doing wrong?

Thanks,
Igor
 
J

Jason Foreman

I have two classes Album and Korisnik (think about that as user),
they are connected with album_korisnik table (I have pluralization
turned off).

Her is the declaration:

class Album < ActiveRecord::Base
...
has_and_belongs_to_many :prijatelji, :class_name => 'Korisnik'
...

class Korisnik < ActiveRecord::Base
...
has_and_belongs_to_many :albumi_prijatelja, :class_name => 'Album'
...

I'm trying to add new korisnik to the album, and this is not working:
prijatelji << k
but this line is working ok
k.albumi_prijatelja << self

In the first case i don't get any error in the log, and don't get any
sql commands in transaction.

What I'm doing wrong?

Thanks,
Igor


This should work:
a = Album.find(1) # find an album
k = Korisnik.find(1) # find a Korisnik
a.prijatelji << k # add the Korisnik to the album

Converserly:
a = Album.find(1) # find an album
k = Korisnik.find(1) # find a Korisnik
k.albumi_prijatelja << a # add the album to the Korisnik


Either way should add to the many-many association.

I assume you are using "k.albumi_prijatelja << self" from inside a
method of the Album class? which is why it might work. If that is
the case, then your first example isn't working because I think it
would need to be "self.prijatelji << k" not just "prijatelji << k".
If you are trying to do this within a controller method, then use the
examples I provided.

HTH,

Jason
 
I

Igor Anic

Sorry,
it was my mistake (as usual).
Both ways are working now.

korisnik_id was an autoincrement field in the database !!!
is it strange that I didn't get failed update statement?

Thank you Jason and sorry for the stupid question.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top