简体   繁体   English

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

[英]How Do I Use A Join Table in Ruby On Rails?

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: 所以我想我的问题是:

  1. Will this join_table work how I have it or is there a better way to have written it? 这个join_table会如何工作,还是有更好的书写方式?

  2. I just wrote the add_index lines in this file. 我只是在该文件中写了add_index行。 Do I have to create indexes from the command line and if so, how do I do that? 我是否必须从命令行创建索引,如果是,该怎么做?

  3. How do I use this join_table in a controller? 如何在控制器中使用此join_table?

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 我希望这个对你有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM