Jeffrey
Jeffrey

Reputation: 63

Rails - Need help understanding Many-Many Association

I'm working on a project that requires a many-many relationship between books and users.

A book can be borrowed by many users (it has a # of copies property to define max # of users it can be borrowed by) and a user can borrow many books.

I created the models and the schema but I'm having trouble understanding how the data is saved in the databases as well as how to access them.

***Models***
class Book < ApplicationRecord

    has_and_belongs_to_many :users
end


class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
  
  has_and_belongs_to_many :books
end

***Schema***
ActiveRecord::Schema.define(version: 2021_10_06_190918) do

  create_table "books", force: :cascade do |t|
    t.string "title"
    t.integer "total_copies"
    t.integer "copies_available"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.integer "book_id"
    t.index ["book_id"], name: "index_books_on_book_id"
  end

  create_table "users", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.string "name"
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
  end

end

After reading some documentation about this has_and_belongs_to_many association I attempted to create the joins table migration with this line: rails g migration book_users user_id:integer book_id:integer However after pushing the migration, it doesn't look like the joins table was created?

What I am looking to do:

  1. As a user, I can click a book to borrow it (adding my userID to the book's "borrowee" list)

  2. I can click a book and display which users are currently borrowing this book

  3. As a user, display which books I am currently borrowing

Upvotes: 0

Views: 44

Answers (1)

mcfoton
mcfoton

Reputation: 335

  • For many-to-many you do need a third table. Note that if using has_and_belongs_to_many your migration should create books_users (note 's' in both cases) table for Rails to recognize it as an intermediate table.
  • My personal preference was always with has_many through because it allows you to have id on the intermediate table and an actual Model file for the relation in case you later want to add more logic to it (validations, sending email on new borrow etc)

https://guides.rubyonrails.org/association_basics.html#choosing-between-has-many-through-and-has-and-belongs-to-many

Upvotes: 1

Related Questions