Rails doesn't generate created_at for fixture

半城伤御伤魂 提交于 2019-12-18 08:52:45

问题


I have a model Question with "question_id", "elapsed_time", "allowed_time" and "status" as its fields and a controller named Reporting that receive JSON containing questions and save it. ("question_id" is not related to any of my models)

So far there is no problem. Until I try to run some tests. I've an error when Rails is trying to load my Question's fixture : ActiveRecord::StatementInvalid: SQLite3::ConstraintException: questions.created_at may not be NULL: INSERT INTO "questions"

Here's my fixture :

one:
  id: 1
  question_id: MyString
  app: MyString
  guid: 1
  status: 1
  elapsed_time: 1
  allowed_time: 1

and my model :

class CreateQuestions < ActiveRecord::Migration
  def change
    create_table :questions do |t|
      t.string :app
      t.integer :guid
      t.string :question_id
      t.integer :elapsed_time
      t.integer :allowed_time
      t.datetime :happened_at
      t.integer :status

      t.timestamps
    end
  end
end

Any idea ?


回答1:


As explained in https://stackoverflow.com/a/4350202/978525 you can add something like the following to your fixture objects:

objectA:
  foo: something
  created_at: <%= 5.day.ago.to_s(:db) %>
  updated_at: <%= 5.day.ago.to_s(:db) %>



回答2:


My model's name was in plural form. Change it to singular and rails will generate timestamp.

See how rails generate timestamp : https://github.com/rails/rails/blob/master/activerecord/lib/active_record/fixtures.rb#L560



来源:https://stackoverflow.com/questions/16548352/rails-doesnt-generate-created-at-for-fixture

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!