无法创建自引用错误

时间:2011-09-01 14:19:37

标签: ruby-on-rails

我最近将此应用程序从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会产生此错误?

1 个答案:

答案 0 :(得分: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

因此您需要在users表和新联接表friends_users中添加其他字段friend_id,其字段为:user_idfriend_id

注意:您可以在那里找到更多信息:http://railsforum.com/viewtopic.php?id=4237

相关问题