这是我的ActiveRecord:
class CreateTasks < ActiveRecord::Migration[6.1]
def change
create_table :tasks do |t|
t.string :title
t.text :body
t.datetime :due
t.integer :priority
t.text :tag
t.timestamps
end
end
end
我试图在内部创建一个对象rails console
并将其保存,但它始终返回false
irb(main):008:0> t =Task.new(title:"First task", body:"body of first task", due:"2020-12-29", priority:2, tag:"tag of first task")
=> #<Task id: nil, title: "First task", body: "body of first task", tag: "tag of first task", due: nil, priority: 2, created_at: nil, updated_at: nil>
irb(main):018:0> t.save
=> false
我检查了多个站点以确保语法正确,但是仍然无法保存该对象
我的任务模型
class Task < ApplicationRecord
belongs_to :container
validates :title, presence: true
validates :body, presence: true, length: { minimum: 10 }
validates :priority, presence: true
validates :due, presence: true
validates :tag, presence: true
end
当您遇到类似问题时,通过在该实例上输出错误很容易调试。因此,当您false
致电给save
justt.errors.full_messages
或call f.valid?
then时,您将返回t.errors.full_messages
。
在new
参数列表中,您缺少container_id
。从文档中看不出来,但是在belongs_to :container
内部添加会为该关联的存在添加验证(除非您通过选项optional: true
)。
此外,正如其他人已经指出的那样,您的数据库缺少用于存储的列,该列container_id
用于存储由创建的关联belongs_to :container
。
因此,要解决您的问题,您必须做两件事:
Container
模型,其数据库表,并belongs_to
正确设置关联。container_id
给Task.new
。本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句