【问题标题】:Two foreign keys in a table referencing one primary key in another table using rails migration使用 Rails 迁移的表中的两个外键引用另一个表中的一个主键
【发布时间】:2020-06-27 03:53:32
【问题描述】:

我正在尝试在另一个表中创建一个具有 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

这个方法正确吗?如果是这样,如果我提供受人尊敬的表的 FK,我如何获得输出。

这是我的 Jobapp 表的样子

我尝试使用Jobapp.joins(:user),但无济于事 我应该在模型文件中写belongs_to 或has_many 吗?

【问题讨论】:

    标签: ruby-on-rails database postgresql rubygems relational-database


    【解决方案1】:
    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
    

    【讨论】:

    • jobapps 这个名字很奇怪。
    • @jobapps = JobApp.includes(:job).all; @jobapps.each { |j| puts j.job.name }
    • 如果你真的想做一个简单的连接而不是加载关联的模型,你需要从作业@jobapps = JobApp.joins(:job).select('jobapps.*', 'jobs.name AS job_name'); @jobapps.each { |j| puts j.job_name }中选择行
    • 那是因为表被命名为jobs 而不是job'jobs.title AS job_title'.
    • 老兄。再次阅读该代码。您正在选择“jobs.title AS job_title”。足够的后续问题。
    猜你喜欢
    • 2023-03-17
    • 2011-01-11
    • 1970-01-01
    • 2020-08-14
    • 2017-01-16
    • 2019-12-23
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    相关资源
    最近更新 更多