需要使用add_index关于移民的belongs_to的/的has_many关系? (Rails的3.2,活动记录) [英] Need to use add_index on migration for belongs_to/has_many relationship? (Rails 3.2, Active Record)

查看:152
本文介绍了需要使用add_index关于移民的belongs_to的/的has_many关系? (Rails的3.2,活动记录)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题很简单,但我没能找到一个明确的答案。

我建一个团购Rails应用程序。

  • 每个交易都有很多产品(的has_many)

  • 每个产品属于交易

如下因素2.3从 Rails的指南,我会用这在我的迁移:

 类CreateDeal< ActiveRecord的::迁移
    高清变化
      CREATE_TABLE:交易做| T |
        t.string:名称
        t.timestamps
      结束

      CREATE_TABLE:做产品| T |
        t.belongs_to:新政
        t.timestamps
      结束
    结束
   结束
 

自动,轨道/主动记录将添加在产品表中的列deals_id吧?

我是否需要加入到我的迁移 add_index 或者是做的原因是belongs_to的的自动/手动添加一个索引这个deals_id列(如下图所示)的has_many关系,我已经设置?

  CREATE_TABLE:做产品| T |
  t.belongs_to:新政
  t.timestamps

  add_index:产品:deals_id
结束
 

解决方案

您确实需要添加索引自己...但是,如果你使用命令行生成的模型,并使用belongs_to的,Rails会添加索引到迁徙...

例如。

 导轨G型产品的交易:belongs_to的
 

会产生

 类CreateProducts< ActiveRecord的::迁移
  高清变化
    创建表:做产品| T |
      t.belongs_to:交易

      t.timestamps
    结束
    add_index:产品:deal_id
  结束
结束
 

My question is quite simple but I failed to find a clear answer.

I build a daily deals Rails app.

  • Each deal has many products (has_many)

  • Each product belongs to a deal

Folowing 2.3 from Rails Guides, I'll use this in my migration:

   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

Automatically, Rails/active records will add in the Product Table a column deals_id right?

Do I need to add an index on this deals_id column manually (like below) by adding to my migration add_index or is it done "automatically" because of the belongs_to/has_many relationship I have set?

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

  add_index :products, :deals_id 
end

解决方案

You do need to add the index yourself... However, if you use the command line generator for the model and use belongs_to, Rails will add in the index into the migration...

e.g.

rails g model product deal:belongs_to

would produce

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

这篇关于需要使用add_index关于移民的belongs_to的/的has_many关系? (Rails的3.2,活动记录)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆