gpt4 book ai didi

ruby-on-rails - 无法创建自引用错误

转载 作者:行者123 更新时间:2023-12-03 16:06:32 24 4
gpt4 key购买 nike

我最近将这个应用程序从 rails 2.2.2 更新到 2.3.11。升级前一切正常。升级后,我收到以下错误:

ActiveRecord::HasAndBelongsToManyAssociationForeignKeyNeeded in InstrumentsController#arrow
Cannot create self referential has_and_belongs_to_many association on 'Trait#traits'. :association_foreign_key cannot be the same as the :foreign_key.

在礼物模型中:
class Gift < ActiveRecord::Base
has_many :delegate_gifts
has_many :answers

belongs_to :feel_motive, :class_name => "Trait", :foreign_key => "feel_motive_id"
belongs_to :see_motive, :class_name => "Trait", :foreign_key => "see_motive_id"
belongs_to :incline_motive, :class_name => "Trait", :foreign_key => "incline_motive_id"

has_and_belongs_to_many :users
has_and_belongs_to_many :best_contributions

def traits
traits = []
traits << feel_motive unless feel_motive.nil?
traits << see_motive unless see_motive.nil?
traits << incline_motive unless incline_motive.nil?
return traits
end
end

特质模型:
class Trait < Field
has_and_belongs_to_many :traits
end

为什么从 2.2.2 升级到 2.3.11 会产生这个错误?

最佳答案

has_and_belongs_to_many不能指向自己(至少不是以简单的方式)。这就是为什么你有“自我引用”错误的原因。如果你真的需要这个循环关联,那么你必须这样写:

class User < ActiveRecord::Base
has_and_belongs_to_many :friends,
:class_name => "User",
:association_foreign_key => "friend_id",
:join_table => "friends_users"
end

所以你需要额外的字段 friend_id在用户表和新连接表friends_users 中,字段为: user_idfriend_id
注意:您可以在此处找到更多信息: http://railsforum.com/viewtopic.php?id=4237 )

关于ruby-on-rails - 无法创建自引用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7271699/

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