具有特定foreign_key的Has_one关系

时间:2020-04-07 14:02:32

标签: ruby-on-rails ruby activerecord

在我的Task模型中,我想与Pricer模型创建两个has_one关系。为此,我在任务表中添加了:client_pricer_id :presta_pricer_id 值。现在,我想为它们每个创建一个has_one

我的代码:

迁移文件:

class AddPricerToTasks < ActiveRecord::Migration[6.0]
  def change
    add_column :tasks, :client_pricer_id, :integer, foreign_key: true
    add_column :tasks, :presta_pricer_id, :integer, foreign_key: true
  end
end

任务模型

  has_one :client_pricer, :class_name => 'Pricer', :foreign_key => 'client_pricer_id'
  has_one :presta_pricer, :class_name => 'Pricer', :foreign_key => 'presta_pricer_id'

查看:

@task.client_pricer

错误:

SQLException:没有此类列:pricers.presta_pricer_id

我当然忘了在has_one行中指定一个变量。但我不知道是哪一个:)

2 个答案:

答案 0 :(得分:1)

您要使用belongs_to而不是has_one

class Task < ApplicationRecord
  belongs_to :client_pricer, class_name: 'Pricer', inverse_of: :client_pricer_tasks
  belongs_to :presta_pricer, class_name: 'Pricer', inverse_of: :presta_pricer_tasks
end

class Pricer < ApplicationRecord
  has_many :client_pricer_tasks, class_name: 'Task', foreign_key: :client_pricer_id
  has_many :presta_pricer_tasks, class_name: 'Task', foreign_key: :presta_pricer_id
end

由于语义混乱,这是一种非常常见的混淆。

belongs_to将外键放在 this 模型表上。 has_one将其放在另一端。

has_one / has_many的倒数始终为belongs_to。否则,这些关系只会彼此指向一个圆圈。

答案 1 :(得分:0)

我终于发现我的错误必须将has_one更改为belongs_to(因为该密钥位于我的Task模型中)

我的代码:

任务模型:

belongs_to :client_pricer, :class_name => 'Pricer', optional: true
belongs_to :presta_pricer, :class_name => 'Pricer', optional: true
相关问题