【问题标题】:Rails 5 timestamps not working for has_many through modelRails 5 时间戳不适用于 has_many 通过模型
【发布时间】:2020-02-24 01:43:59
【问题描述】:

[ TLDR:检查你的赛程! (见下面的答案)]

gem 'rails', '5.2.3'

我有两个模型,People 和 Puppies,它们处于 has_many“通过”关系。连接模型是 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】:

    哇!

    数据库约束违规实际上根本不是来自&lt;&lt; 或我的测试代码。在我从 has_and_belongs_to_many 转换为 has_many through: 之前,我的固定装置中有一些关联。

    例如:

    some_person:
      email: foo@gmail.com
      puppies:
         - some_puppy
    

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

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

    【讨论】:

      猜你喜欢
      • 2011-01-08
      • 2015-10-27
      • 1970-01-01
      • 2018-03-16
      • 1970-01-01
      • 1970-01-01
      • 2012-12-15
      • 1970-01-01
      • 2017-06-29
      相关资源
      最近更新 更多