I have users and books. It's a many to many relationship, so I created a join table based on questions and answers I found on this site.
class Book < ApplicationRecord
has_and_belongs_to_many :users
end
class User < ApplicationRecord
has_and_belongs_to_many :books
end
class BooksUsersJoinTable < ActiveRecord::Migration[5.0]
def change
create_table :books_users_join_table, :id => false do |t|
t.integer :book_id, index: false
t.integer :user_id, index: false
end
end
add_index(:books_users, [:book_id, :user_id], :unique => true)
add_index(:books_users, :book_id)
add_index(:books_users, :user_id)
end
So I suppose my questions are:
Will this join_table work how I have it or is there a better way to have written it?
I just wrote the add_index lines in this file. Do I have to create indexes from the command line and if so, how do I do that?
How do I use this join_table in a controller?
This is what I use do a join
class BooksController < ApplicationController
def index
@books Book.all.joins(:user)
end
end
I hope that this helps
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.