table 中的两个外键引用另一个 table 中的一个主键使用 rails 迁移
Two foreign keys in a table referencing one primary key in another table using rails migration
我正在尝试创建一个 table,在另一个 table 中使用 2 个 FK 引用 1 个 PK。
class CreateJobapps < ActiveRecord::Migration[5.1]
def change
create_table :jobapps do |t|
t.references :job, foreign_key: { job: :id }, index: { unique: true}
t.references :user, foreign_key: { user: :id }, index: { unique: true}
t.timestamps
end
end
end
这个方法正确吗?如果是这样,如果我提供受人尊敬的 table 的 FK,我将如何获得输出?
这是我的 Jobapp table 的样子
我尝试使用 Jobapp.joins(:user)
但无济于事
我应该在模型文件中写 belongs_to 还是 has_many?
class CreateJobapps < ActiveRecord::Migration[5.1]
def change
create_table :jobapps do |t|
t.references :job, foreign_key: { job: :id }
t.references :user, foreign_key: { user: :id }
t.timestamps
end
# Add a compound index instead - you may need to switch the order to
# tweak the index depending on how it is used.
add_index :jobapps, [:job_id, :user_id], unique: true
end
end
class Jobapp < ApplicationRecord
belongs_to :user
belongs_to :job
end
class User < ApplicationRecord
has_many :jobapps
has_many :jobs, through: :jobapps
end
class Job < ApplicationRecord
has_many :jobapps
has_many :users, through: :jobapps
end
我正在尝试创建一个 table,在另一个 table 中使用 2 个 FK 引用 1 个 PK。
class CreateJobapps < ActiveRecord::Migration[5.1]
def change
create_table :jobapps do |t|
t.references :job, foreign_key: { job: :id }, index: { unique: true}
t.references :user, foreign_key: { user: :id }, index: { unique: true}
t.timestamps
end
end
end
这个方法正确吗?如果是这样,如果我提供受人尊敬的 table 的 FK,我将如何获得输出?
这是我的 Jobapp table 的样子
我尝试使用 Jobapp.joins(:user)
但无济于事
我应该在模型文件中写 belongs_to 还是 has_many?
class CreateJobapps < ActiveRecord::Migration[5.1]
def change
create_table :jobapps do |t|
t.references :job, foreign_key: { job: :id }
t.references :user, foreign_key: { user: :id }
t.timestamps
end
# Add a compound index instead - you may need to switch the order to
# tweak the index depending on how it is used.
add_index :jobapps, [:job_id, :user_id], unique: true
end
end
class Jobapp < ApplicationRecord
belongs_to :user
belongs_to :job
end
class User < ApplicationRecord
has_many :jobapps
has_many :jobs, through: :jobapps
end
class Job < ApplicationRecord
has_many :jobapps
has_many :users, through: :jobapps
end