ruby-on-rails - Rails has_and_belongs_to_many 迁移

标签 ruby-on-rails ruby-on-rails-3 migration has-and-belongs-to-many

我有两个模型 restaurantuser,我想对它们执行 has_and_belongs_to_many 关系。

我已经进入模型文件并添加了 has_and_belongs_to_many :restaurantshas_and_belongs_to_many :users

我认为此时我应该能够做类似 Rails 3 的事情:

rails generate migration ....

但我尝试过的一切似乎都失败了。我确信这非常简单,我是 Rails 新手,所以我仍在学习。

最佳答案

您需要添加一个单独的联接表,其中仅包含 restaurant_iduser_id(无主键),并按字母顺序排列。

首先运行迁移,然后编辑生成的迁移文件。

Rails 3

rails g migration create_restaurants_users_table

Rails 4:

rails g migration create_restaurants_users

Rails 5

rails g migration CreateJoinTableRestaurantUser restaurants users

来自docs :

There is also a generator which will produce join tables if JoinTable is part of the name:

<小时/>

您的迁移文件(请注意 :id => false;它会阻止创建主键):

Rails 3

class CreateRestaurantsUsers < ActiveRecord::Migration
  def self.up
    create_table :restaurants_users, :id => false do |t|
        t.references :restaurant
        t.references :user
    end
    add_index :restaurants_users, [:restaurant_id, :user_id]
    add_index :restaurants_users, :user_id
  end

  def self.down
    drop_table :restaurants_users
  end
end

Rails 4

class CreateRestaurantsUsers < ActiveRecord::Migration
  def change
    create_table :restaurants_users, id: false do |t|
      t.belongs_to :restaurant
      t.belongs_to :user
    end
  end
end

t.belongs_to 将自动创建必要的索引。 defchange 将自动检测前向或回滚迁移,无需向上/向下。

Rails 5

create_join_table :restaurants, :users do |t|
  t.index [:restaurant_id, :user_id]
end

注意:还有一个自定义表名称选项,可以作为参数传递给名为 table_name 的 create_join_table。来自 docs

By default, the name of the join table comes from the union of the first two arguments provided to create_join_table, in alphabetical order. To customize the name of the table, provide a :table_name option:

关于ruby-on-rails - Rails has_and_belongs_to_many 迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6561330/

相关文章:

ruby-on-rails - Rails - 获取不带 GET 参数的当前 url

ruby-on-rails-3 - Ruby-on-Rails 使用 jquery mobile,重定向不更改 url

python - 如何以编程方式为 Django 中的给定模型生成 CREATE TABLE SQL 语句?

php - 我如何解决 Laravel 数据库中的迁移?

mysql - 从 MS SQL 迁移到 MySQL : SQLOLEDB? 迁移套件登录错误?

ruby-on-rails - rails : Cast string field to integer in where clause

ruby-on-rails - 命令结束时显示 Errno : :EEXIST Message

javascript - 一些代码让我在这个 gem 中感到困惑 ----backbone-bootstrap-rails

ruby-on-rails - Rails 3使用自定义消息验证许多列的存在

ruby-on-rails - 我如何使用路由别名改进重定向