gpt4 book ai didi

ruby-on-rails - Rails 多对多 SQLite3 错误

转载 作者:行者123 更新时间:2023-12-03 17:50:08 26 4
gpt4 key购买 nike

我在 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

最佳答案

我不知道这是否是您的问题的原因,但是 has_and_belongs_to_many不推荐使用关联。

根据Rails Guide :

The use of extra attributes on the join table in a has_and_belongs_to_many association is deprecated. If you require this sort of complex behavior on the table that joins two models in a many-to-many relationship, you should use a has_many :through association instead of 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

关于ruby-on-rails - Rails 多对多 SQLite3 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11300570/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com