【发布时间】: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_at 和 updated_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