加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 对于belongs_to / has_many关系的迁移,需要使

发布时间:2020-12-16 21:37:17 所属栏目:百科 来源:网络整理
导读:我的问题很简单,但我找不到明确的答案. 我建立了每日优惠Rails应用程序. 每笔交易都有很多产品(has_many) 每个产品都属于一笔交易 从Rails Guides开始,我将在迁移过程中使用它: class CreateDeal ActiveRecord::Migration def change create_table :deals d
我的问题很简单,但我找不到明确的答案.

我建立了每日优惠Rails应用程序.

>每笔交易都有很多产品(has_many)
>每个产品都属于一笔交易

从Rails Guides开始,我将在迁移过程中使用它:

class CreateDeal < ActiveRecord::Migration
    def change
      create_table :deals do |t|
        t.string :name
        t.timestamps
      end

      create_table :products do |t|
        t.belongs_to :Deal
        t.timestamps
      end
    end
   end

自动,Rails /活动记录会在产品表中添加一列Transactions_id对吗?

我是否需要通过添加到我的迁移add_index手动(如下所示)在此deals_id列上添加索引,还是因为我设置的belongs_to / has_many关系而“自动”完成?

create_table :products do |t|
  t.belongs_to :Deal
  t.timestamps

  add_index :products,:deals_id 
end

解决方法

您确实需要自己添加索引…但是,如果您对模型使用命令行生成器并使用belongs_to,则Rails会将索引添加到迁移中…

例如

rails g model product deal:belongs_to

会产生

class CreateProducts < ActiveRecord::Migration
  def change
    create table :products do |t|
      t.belongs_to :deal

      t.timestamps
    end
    add_index :products,:deal_id
  end
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读