SQLite3::ConstraintException: xxxxx.created_at may not be NULL

跟風遠走 提交于 2019-12-24 02:56:25

问题


I have a resque job that creates an artist and associates it with a user. User has_and_belongs_to_many :artists, and Artist has_and_belongs_to_many :users.

def self.perform(itunes_id, user_id=nil)
  artist = Artist.find_by_itunes_id(itunes_id) || lookup_and_create_artist(itunes_id)
  if user_id && user = User.find(user_id)
    user.artists << artist
    user.save!
  end
end

user.artists << artist raises this exception:

ActiveRecord::StatementInvalid: SQLite3::ConstraintException: artists_users.created_at may not be NULL: INSERT INTO "artists_users" ("artist_id", "user_id")

I have also seen the creation of an artists_genres (Artist and Genre have a reciprocal HABTM relationship as well)

ActiveRecord::StatementInvalid: SQLite3::ConstraintException: artists_genres.created_at may not be NULL: INSERT INTO "artists_genres" ("artist_id", "genre_id")

回答1:


Turns out this is purposeful in Rails, but has been raised in numerous issues:

  • https://github.com/rails/rails/issues/7732
  • https://github.com/rails/rails/issues/7735
  • https://github.com/rails/rails/issues/4653
  • https://github.com/rails/rails/pull/4682

HABTM relationships don't automatically set timestamps so I can either remove them or use a has_many :artists, :through => :artists_genres relationship




回答2:


Sounds like your timestamps are not set correctly.

If you wanted to band-aid your way out of it, redefine those two fields as NULLable (instead of NOT NULL).

The problem usually occurs when the app is mis-configured.

Make sure that

config.active_record.record_timestamps = true

If it is false, then the timestamps will not be set and you'll get the constraint error you're seeing.




回答3:


Sounds like your migration does not set the timestamp fields correctly. This is what it should look like:

create_table :artists_users, :id => false do |t|
  t.references :artist
  t.references :user
  t.timestamps
end

create_table :artists_genres, :id => false do |t|
  t.references :artist
  t.references :genre
  t.timestamps
end


来源:https://stackoverflow.com/questions/13464299/sqlite3constraintexception-xxxxx-created-at-may-not-be-null

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