Unable to create self-relational error

I recently updated this application from rails 2.2.2 to 2.3.11. Before the upgrade, everything went fine. After updating, I get the following error:

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.

In the gift model:

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

attribute model:

class Trait < Field
  has_and_belongs_to_many :traits
end

Why does updating from 2.2.2 to 2.3.11 cause this error?

+5
source share
1 answer

has_and_belongs_to_manycannot point to himself (at least not so easily). That is why you have a "self-referential" error. If you really need this repeating association, then you need to write something like this:

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

so you need an extra field friend_idin the users table and a new join friends_users table with the fields: user_idandfriend_id

: : http://railsforum.com/viewtopic.php?id=4237)

+13

All Articles