在我的模型中添加非标准外键的正确方法? Ruby on Rails

问题描述 投票:0回答:1

我有一个表需要引用另一个表而不使用外键的id列。

我有这两个模型:

class MatchReference < ApplicationRecord
    belongs_to :summoner, :foreign_key => 'accountId'
end


class Summoner < ApplicationRecord
    has_many :match_references
end

我创建了这个迁移,将它们与Summoner.accountId链接在一起:

class AddAccountIdToMatchReferences < ActiveRecord::Migration[5.1]
  def change
    add_reference :match_references, :summoner, column: :accountId, foreign_key: true
  end
end

请注意,match_references应该使用的外键是summoners.accountId而不是summoners.id

运行迁移后我得到了这个模式:

create_table "match_references", force: :cascade do |t|
  t.string "lane"
  t.bigint "gameId"
  t.integer "champion"
  t.string "platformId"
  t.integer "season"
  t.integer "queue"
  t.string "role"
  t.bigint "timestamp"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.bigint "summoner_id"
  t.index ["summoner_id"], name: "index_match_references_on_summoner_id"
end


create_table "summoners", force: :cascade do |t|
  t.bigint "profileIconId"
  t.string "name"
  t.integer "summonerLevel"
  t.datetime "revisionDate"
  t.bigint "league_id"
  t.bigint "accountId"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

我希望能够做到这样的事情:

  s = Summoner.last
  s.match_references.last.gameId # => 123456789

  m = MatchReference.new
  m.summoner_id = s.accountId
  m.game_id = 1234
  m.champion = 123
  ...
  m.save!

但我得到一个错误说:

ActiveRecord::RecordInvalid: Validation failed: Summoner must exist
from /Users/hebrongeorge/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.4/lib/active_record/validations.rb:78:in `raise_validation_error'
ruby-on-rails ruby postgresql
1个回答
0
投票

这应该工作:

class Summoner < ApplicationRecord
 self.primary_key = 'accountId'
 has_many :match_references, :foreign_key => 'accountId'
end

class MatchReference < ApplicationRecord
 belongs_to :summoner
end
© www.soinside.com 2019 - 2024. All rights reserved.