2

レールで多対多の関係を作成しました。これが私のモデルと移行です

class Channel < ActiveRecord::Base
  has_and_belongs_to_many :packages
  validates_presence_of :name
end

class Package < ActiveRecord::Base
  has_and_belongs_to_many :channels
  validates_presence_of :name
end

class CreateChannelsPackages < ActiveRecord::Migration
  def change
    create_table :channels_packages, :id => false do |t|
      t.references :channel
      t.references :package

      t.timestamps
    end
    add_index :channels_packages, :channel_id
    add_index :channels_packages, :package_id
  end
end

次に、複数選択がありますが、保存しようとするとこのエラーが発生します

SQLite3::ConstraintException: constraint failed: INSERT INTO "channels_packages" ("package_id", "channel_id") VALUES (1, 1)

移行からインデックスを削除しようとしましたが、解決しませんでした。他の誰かがこの問題を抱えていましたか?

ところで、私はRails 3.2.6とsqlite3 1.3.6を使用しています

4

2 に答える 2

2

I think gabrielhilal's answer is not quite correct: use of extra attributes in the join table is deprecated, thus you need to remove the timestamp in your migration, then it should work just fine with the has_and_belongs_to_many wich itself is not deprecated.

If you do need additional attributes in your join table, though, has_many :through is the way to go.

There is also another question with good answers on this topic: Rails migration for has_and_belongs_to_many join table

于 2012-07-05T22:22:09.947 に答える
1

それがあなたの問題の原因であるかどうかはわかりませんが、has_and_belongs_to_many関連付けは廃止されました。

Railsガイドによると:

has_and_belongs_to_manyアソシエーションの結合テーブルでの追加の属性の使用は非推奨になりました。多対多の関係で2つのモデルを結合するテーブルでこの種の複雑な動作が必要な場合は、has_and_belongs_to_manyの代わりにhas_many:throughアソシエーションを使用する必要があります。

結合テーブルに属性を追加していないことはわかっていますが、移行を以下に変更してみてください。これがデフォルトだと思います。

class CreateChannelPackageJoinTable < ActiveRecord::Migration
  def change
    create_table :channels_packages, :id => false do |t|
      t.integer :channel_id
      t.integer :package_id

      t.timestamps
    end
  end
end
于 2012-07-02T23:28:12.777 に答える