通过模型设置has_many的5个时间戳无效

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

[TLDR:检查设备! (请参见下面的答案)]

gem 'rails', '5.2.3'

我有两个模型,分别为has_many“ through”关系中的People和Puppies。连接模型为Companion。

class Person < ApplicationRecord
    has_many :companions, -> { order(created_at: :asc) }
    has_many :puppies, through: :companions

class Puppy < ApplicationRecord
    has_many :companions
    has_many :people, through: :companions

class Companion < ApplicationRecord
    self.table_name = 'people_puppies' #is the table name messing things up?
    belongs_to :person
    belongs_to :puppy
    default_scope { order(created_at: :asc) }

我的问题是created_atupdated_at时间戳不适用于Companion模型。当我尝试在两个记录之间分配新关系时...

    @person.puppies << some_puppy
    # or
    @person.companions << some_puppy
    # or
    Companion.create!(puppy: some_puppy, person: @person)

...我收到数据库约束违规消息:

ActiveRecord::NotNullViolation: SQLite3::ConstraintException: NOT NULL constraint failed: people_puppies.created_at: INSERT INTO "people_puppies" ("person_id", "puppy_id") VALUES (1052040621, 904095534)

为什么Rails不添加时间戳?

这里是架构:

  create_table "people_puppies", force: :cascade do |t|
    t.integer "person_id", null: false
    t.integer "puppy_id", null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["person_id", "puppy_id"], name: "index_people_puppies_on_person_id_and_puppy_id"
    t.index ["puppy_id", "person_id"], name: "index_people_puppies_on_puppy_id_and_person_id"
  end
ruby-on-rails ruby-on-rails-5 rails-activerecord has-many-through has-many
1个回答
1
投票

WOOPS!

DB约束违反实际上根本不是来自<<或我的测试代码。从我从has_and_belongs_to_many转换为has_many through:]之前,我的装置中有剩余的关联

Ex:

some_person:
  email: [email protected]
  puppies:
     - some_puppy

^这是在我的测试代码开始之前导致数据库错误的原因。 :-/

我最初的问题是基于错误的假设,但是如果您从HABTM重构为has_many through(并且您已经有了固定装置),这似乎是一个容易犯的错误。因此,即使这很尴尬,我也将保留此问题,以防将来对某人有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.