具有相同表轨的多个关联

时间:2016-01-30 16:23:54

标签: ruby-on-rails

我有两个类User和Bug有两个外键在bug中引用user_id ..问题是我如何在创建记录时将user_id存储在外键列中。例如,如果用户输入bug然后他的id存储在buger_id colunm中。

类Bug

belongs_to :buger, class_name: "User", foreign_key: "buger_id"
belongs_to :developer , class_name: "User", foreign_key: "developer_id"

班级用户

has_many :created_bugs, class_name:"bugs"
has_many :developed_bugs, class_name:"bugs"

3 个答案:

答案 0 :(得分:2)

您需要将foreign_key添加到has_many声明中!

  class User < ActiveRecord::Base
    has_many :created_bugs, class_name: 'Bug'   , foreign_key: :buger_id
    has_many :developed_bugs, class_name: 'Bug' , foreign_key: :developer_id
  end

  class Bug < ActiveRecord::Base
    belongs_to :buger, class_name: 'User'
    belongs_to :developer , class_name: 'User'
  end

另请参阅:http://guides.rubyonrails.org/association_basics.html

答案 1 :(得分:0)

您也可以在has_many行上指定类和外键。

has_many :created_bugs, class_name:"Bug", foreign_key: 'buger_id'
has_many :developed_bugs, class_name:"Bug", foreign_key: 'developer_id'

答案 2 :(得分:0)

在Rails 5.1或更高版本中,您可以这样做:

迁移

class CreateBug < ActiveRecord::Migration
   def change
    ccreate_table(:bugs) do |t|
        t.references :bugger, foreign_key: { to_table: 'users' }
        t.references :developer, foreign_key: { to_table: 'users' }
    end
  end
end

这将创建字段bugger_iddeveloper_id,并在数据库级别引用users

模型

class Bug < ActiveRecord::Base
  belongs_to :bugger, class_name: "User"
  belongs_to :developer, class_name: "User"
end

class User < ActiveRecord::Base
  has_many :created_bugs, class_name: "Bug", foreign_key: "bugger_id"
  has_many :developed_bugs, class_name: "Bug", foreign_key: "developer_id"
end

FactoryBot

如果您使用FactoryBot,则您的工厂可能看起来像这样:

FactoryBot.define do
  factory :bug do
    association :bugger, factory: :user
    association :developer, factory: :user
  end
end