2011-09-01 70 views
5

我最近更新了这个应用程序从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农产品这个错误?

+0

“无法创建自我”。毫无疑问,听起来有人认为存在主义有点过于严肃。 – Layke

+1

你可以编辑你的问题,包括你的'特质'模型的代码。 –

+0

@JohnTopley oops ...添加到帖子的特质模型。 – Jay

回答

13

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