在我的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行中指定一个变量。但我不知道是哪一个:)
答案 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