如何添加新表并将其与上一个表链接,并在ruby中添加索引

时间:2015-11-01 07:50:55

标签: ruby-on-rails dependencies

我有这个表结构:

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :username 
      t.string :email
      t.string :encrypted_password 
      t.string :salt
      t.timestamps
    end
  end
end

我想添加一个新表,如下所示:

class CreateHolidays < ActiveRecord::Migration
  def change
    create_table :holidays do |t|
      t.string :earn_leave
      t.string :seek_leave
      t.string :unplanned_leave
      t.timestamps
      t.timestamps
    end
    add_index(users,id)
  end
end

我应该怎么做,请同时建议可以/应该用于迁移的命令。

1 个答案:

答案 0 :(得分:0)

您想要查看foreign_keys

#app/models/holiday.rb
class Holiday < ActiveRecord::Base
   belongs_to :user
end

#app/models/user.rb
class User < ActiveRecord::Base
   has_many :holidays
end

这意味着您必须add the user_id foreign keyholidays数据表:

class CreateHolidays < ActiveRecord::Migration
  def change
    create_table :holidays do |t|
      t.references :user 
      t.string :earn_leave
      t.string :seek_leave
      t.string :unplanned_leave
      t.timestamps
      t.timestamps
    end
  end
end

您必须记住,Rails旨在构建在relational database之上。因此,它在locate associated records的表格中使用foreign_keys

enter image description here

以上将允许您致电:

@user.holidays

@holiday.user