Reputation: 391
I have 3 models in my Ruby on Rails say publisher, author and book. I want to create many to many relationship among them.
I have created a table called authors_books_publishers and added has_many_and_belongs_to in them.. for e.g.
Author
has_many_and_belongs_to :books
has_many_and_belongs_to :publishers
Book
has_many_and_belongs_to :authors
has_many_and_belongs_to : publishers
Publisher
has_many_and_belongs_to :authors
has_many_and_belongs_to :books
But it doesn't work when I try to add books in author
a = Author.new
b = Book.new
a.books << b
It says (and rightly so) that system doesn't find a table called authors_books.
Please help
P.S. please treat the above models as e.g. They are not the real names in my app.
Thanks,
Upvotes: 0
Views: 1993
Reputation: 4702
I did an article on active record associations a little while ago, here's the link;
http://mikeyhogarth.wordpress.com/2010/12/19/basic-activerecord-associations-overview/
I think it may involve the :through symbol. I am by no means a rails expert (trying to become one!) but hopefully that'll help.
Upvotes: 0
Reputation: 33257
you have to create 3 separate tables:
authors_books
books_publishers
authors_publishers
and you probably the authors_publishers
association is redundant b/c you could do same thing with author has_many :publishers, :thorough => :books
Upvotes: 1