删除has_one通过:关联

时间:2017-11-21 14:29:20

标签: ruby-on-rails activerecord

我有

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

似乎我在某处失败了,它找不到要销毁的列。

1 个答案:

答案 0 :(得分:0)

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

  
    

Active Record没有内置的复合主键支持

  
     

这意味着您无法操作其对应表未定义单列主键的模型。这包括通过使用该模型的协会这样做。

所以在我的情况下,选择create_join_table不是正确的选择。而是创建一个普通的表。

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