我有这个表结构:
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
我应该怎么做,请同时建议可以/应该用于迁移的命令。
答案 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 key到holidays
数据表:
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
:
以上将允许您致电:
@user.holidays
和
@holiday.user