Cannot create self referential error
I recently updated this application from rails 2.2.2 to 2.3.11. Everything was running fine before the upgrade. After the upgrade i am getting the following error:
ActiveRecord::HasAndBelongsToManyAssociationForeignKeyNeeded in InstrumentsControl开发者_JS百科ler#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 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
trait model:
class Trait < Field
has_and_belongs_to_many :traits
end
Why does upgrading from 2.2.2 to 2.3.11 produce this error?
has_and_belongs_to_many
can not point to itself (at least not in the easy way). That is why you have "self referential" error. If you really need this recurrent association then you have 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 additional field friend_id
in users table and new join table friends_users with fields: user_id
and friend_id
Note: more information you can find there: http://railsforum.com/viewtopic.php?id=4237)
精彩评论