Hello,
If i have a has_many and an HABTM relationship what is the best way to
manage this? I.E.,
user
id
username
has_many :books
books
id
user_id
bookname
belongs_to :user
Now what I also want is people to be able to share books with each
other. So
i have shared_books table , with user_id, book_id which to me is an
HABTM
relationship. How do I have both associations co-exist in the model ?
Adam
use something like the following (untested)
user.rb
each user can share a number of books
has_and_belongs_to_many :shared_books, :join_table => ‘shared_books’,
:class_name => ‘book’
book.rb
a book can belong to many users
has_and_belongs_to_many :shared_users, :join_table => ‘shared_books’,
:class_name => ‘user’
Mike
thanks I will try this. I wasnt sure if you can do
has_many :books
has_and_belongs_to_many :shared_books, :join_table => ‘shared_books’,
:class_name => ‘book’
in the same model.
Adam
unfortunately this didnt work… i had this in my User model
has_many :books
has_and_belongs_to_many :shared_books, :join_table => ‘shared_books’,
:class_name => :book
and this in the book model
belongs_to :user
has_and_belongs_to_many :shared_books, :join_table => ‘shared_books’,
:class_name => :user
TypeError: can’t convert Symbol into String
from
/usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/base.rb:1087:in
type_name_with_module' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/base.rb:1356:in
compute_type’
from
/usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/reflection.rb:125:in
klass' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/associations/has_and_belongs_to_many_association.rb:158:in
construct_sql’
from
/usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/associations/has_and_belongs_to_many_association.rb:6:in
initialize' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/associations.rb:934:in
shared_books’
from (irb):2
Change :class_name => :book to :class_name => ‘book’
Khurram Ijaz
http://www.renai-soft.com
— :class_name => “Book”, I think.
Khurram Ijaz wrote:
Change :class_name => :book to :class_name => ‘book’
Khurram Ijaz
http://www.renai-soft.com