2

アーティストを作成し、それをユーザーに関連付ける resque ジョブがあります。ユーザー has_and_belongs_to_many :artists、およびアーティスト 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この例外を発生させます:

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

私はまた、artists_genres の作成を見てきました (Artist と Genre にも相互 HABTM 関係があります)。

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

3 に答える 3

3

これは Rails では意図的なものであることが判明しましたが、多くの問題で提起されています。

HABTM リレーションシップはタイムスタンプを自動的に設定しないため、タイムスタンプを削除するかhas_many :artists, :through => :artists_genresリレーションシップを使用できます

于 2012-11-20T20:26:47.113 に答える
0

タイムスタンプが正しく設定されていないようです。

応急処置をしたい場合は、これらの 2 つのフィールドをNULL(の代わりに) 有能として再定義しNOT NULLます。

この問題は通常、アプリの構成が間違っている場合に発生します。

ことを確認してください

config.active_record.record_timestamps = true

false の場合、タイムスタンプは設定されず、表示されている制約エラーが発生します。

于 2012-11-19T23:45:07.447 に答える
0

移行でタイムスタンプ フィールドが正しく設定されていないようです。これは次のようになります。

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
于 2012-11-19T23:46:01.177 に答える