หากคุณต้องการสร้างuser_idมันจะเป็นข้อสันนิษฐานที่สมเหตุสมผลว่าคุณกำลังอ้างถึงตารางผู้ใช้ ในกรณีนี้การโยกย้ายจะต้อง:
rails generate migration AddUserRefToProducts user:references
คำสั่งนี้จะสร้างการย้ายข้อมูลต่อไปนี้:
class AddUserRefToProducts < ActiveRecord::Migration
def change
add_reference :user, :product, index: true
end
end
หลังจากรันrake db:migrateทั้งuser_idคอลัมน์และดัชนีจะถูกเพิ่มลงในproductsตาราง
ในกรณีที่คุณเพียงแค่ต้องเพิ่มดัชนีเพื่อคอลัมน์ที่มีอยู่เช่นnameของuserตารางเทคนิคต่อไปนี้อาจจะมีประโยชน์:
rails generate migration AddIndexToUsers name:string:index จะสร้างการย้ายข้อมูลต่อไปนี้:
class AddIndexToUsers < ActiveRecord::Migration
def change
add_column :users, :name, :string
add_index :users, :name
end
end
ลบadd_columnบรรทัดและเรียกใช้การย้ายข้อมูล
ในกรณีที่อธิบายไว้คุณสามารถออกrails generate migration AddIndexIdToTable index_id:integer:indexคำสั่งแล้วลบadd_columnบรรทัดจากการย้ายข้อมูลที่สร้างขึ้น แต่ขอแนะนำให้เลิกทำการย้ายข้อมูลครั้งแรกและเพิ่มข้อมูลอ้างอิงแทน:
rails generate migration RemoveUserIdFromProducts user_id:integer
rails generate migration AddUserRefToProducts user:references