我有两个模型restaurantuser,我想执行一个has_和_-besides_-to_-many关系.

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

我想在这一点上,我应该可以做一些类似Rails 3的事情:

rails generate migration ....

但我try 过的一切似乎都失败了.我相信这很简单,我对rails还不熟悉,所以我还在学习.

推荐答案

您需要在alphabetical order中添加一个单独的联接表,其中只有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人中:

还有一个生成器,它将在JoinTable时生成join表


Your migration file (note the :id => false; it's what prevents the creation of a primary key):

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将自动创建必要的索引.自动上移或下移都不需要.

Rails 5

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

注意:还有一个自定义表名选项,可以作为参数传递,以创建名为table_name的_join_表.从docs

默认情况下,联接表的名称来自

Ruby-on-rails相关问答推荐

如何修改使用Google Cloud App Engine部署rails 7应用程序的步骤

错误AESGCMOpen获取密码:消息身份验证失败:Golang解密GCM

多对多模型通过控制台创建记录不起作用

Sweet Alert 2 在 Rails 7 应用程序中无法正常工作

插件和 Ruby gem 之间的区别?

Rails ActiveRecord 中的更新插入

在哈姆尔与当地人进行局部渲染?

I18n 用于特定于模型的 Rails 提交按钮

在 Rails 3.2 中更新多行

在 Rails 中找不到关联问题

rails, activerecord, 获取当前连接规范

如何让 Rspec 运行嵌套在文件夹下的所有测试?

关于在不适合任何地方的 Rails 应用程序中放置类的指南

批量查找 mongoDB 记录(使用 mongoid ruby​​ 适配器)

Ruby 和 Ruby on Rails 离线 API 文档

在范围内传递参数

错误:无法构建 gem 原生扩展 - 安装 mysql2 时出错

反编译开发assets资源 管道

Coffeescript ||= 模拟?

如何删除特殊字符?