delete has_one通过:关联



我有

class Job < ApplicationRecord
  has_one :user, through: :jobs_user
  has_one :jobs_user, dependent: :destroy
end

和join_table的模型看起来像:

class JobsUser < ApplicationRecord
  belongs_to :job
  belongs_to :user
end

迁移是:

create_join_table :jobs, :shops do |t|
  t.index :job_id
end

当我创建作业并尝试删除其失败时:

j = Job.create(user: User.last)
j.destroy!
  Job Load (0.3ms)  SELECT  "jobs".* FROM "jobs"  ORDER BY "jobs"."id" DESC LIMIT 1
   (0.2ms)  BEGIN
  JobsShop Load (0.3ms)  SELECT  "jobs_shops".* FROM "jobs_shops" WHERE "jobs_shops"."job_id" = 21365 LIMIT 1  [["job_id", 21365]]
  SQL (0.7ms)  DELETE FROM "jobs_shops" WHERE "jobs_shops"."" = NULL  [[nil, nil]]
   (0.2ms)  ROLLBACK
ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  zero-length delimited identifier at or near """"
LINE 1: DELETE FROM "jobs_shops" WHERE "jobs_shops"."" = NULL
                                                      ^
: DELETE FROM "jobs_shops" WHERE "jobs_shops"."" = NULL

看来我在某个地方失败了,找不到销毁的列。

可以在此处找到答案:https://github.com/rails/rails/rails/issues/25347#issuecomment-300067025

主动记录没有内置支持复合主键

这意味着您无法操纵相应表的模型未定义单列主键。其中包括通过使用上述模型的关联进行。

因此,就我而言,选择create_join_table不是正确的选择。而是创建一个普通的表。

create_table :users_jobs do |t|
  t.integer :user_id
  t.integer :job_id
  # t.index :job_id
end

最新更新