我有用户和书籍。这是一个多对多的关系,所以我根据我在这个网站上找到的问题和答案创建了一个连接表。
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
所以我想我的问题是:
这个join_table会如何运作,还是有更好的方式来编写它?
我刚在这个文件中写了add_index行。我是否必须从命令行创建索引,如果是,我该怎么做?
如何在控制器中使用此join_table?
答案 0 :(得分:0)
这就是我使用的连接
{{1}}
我希望这有助于