如何在Ruby On Rails中使用连接表?

时间:2017-04-26 14:40:46

标签: ruby-on-rails ruby-on-rails-5

我有用户和书籍。这是一个多对多的关系,所以我根据我在这个网站上找到的问题和答案创建了一个连接表。

 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

所以我想我的问题是:

  1. 这个join_table会如何运作,还是有更好的方式来编写它?

  2. 我刚在这个文件中写了add_index行。我是否必须从命令行创建索引,如果是,我该怎么做?

  3. 如何在控制器中使用此join_table?

1 个答案:

答案 0 :(得分:0)

这就是我使用的连接

{{1}}

我希望这有助于