【问题标题】:Rails Many to Many SQLite3 errorRails 多对多 SQLite3 错误
【发布时间】:2012-07-03 06:35:15
【问题描述】:

我在 Rails 中创建了多对多关系,这是我的模型和迁移

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

【问题讨论】:

    标签: ruby-on-rails sqlite ruby-on-rails-3.2


    【解决方案1】:

    我认为 gabrielhilal 的回答不太正确:在连接表中使用 extra attributes 已被弃用,因此您需要在迁移中删除时间戳,然后它应该可以与 has_and_belongs_to_many 一起正常工作它本身是弃用的。

    但是,如果您确实需要在连接表中添加其他属性,has_many :through 是可行的方法。

    关于这个主题还有另一个问题有很好的答案: Rails migration for has_and_belongs_to_many join table

    【讨论】:

    • 感谢您的澄清,这解决了我的问题
    【解决方案2】:

    我不知道这是否是您的问题的原因,但 has_and_belongs_to_many 关联已被弃用。

    根据Rails Guide

    已弃用在 has_and_belongs_to_many 关联中的连接表上使用额外属性。如果您需要在表上以多对多关系连接两个模型的这种复杂行为,则应使用 has_many :through 关联而不是 has_and_belongs_to_many。

    我知道您没有向连接表添加任何额外属性,但尝试将迁移更改为以下内容,我认为是default

    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
    

    【讨论】:

    • 谢谢,使用 has_many :through 代替 has_and_belongs_to_many 有效,尽管 has_and_belongs_to_many 在 mysql 上正常工作。迁移与它无关,我可以正常使用 .references 和 add_index
    猜你喜欢
    • 2022-08-21
    • 1970-01-01
    • 2014-03-25
    • 2013-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-28
    相关资源
    最近更新 更多