ruby-on-rails-3 – Rails HABTM自连接错误
发布时间:2020-12-17 04:18:58 所属栏目:百科 来源:网络整理
导读:在我的应用程序中,用户可以关注许多用户,并且可以跟随许多用户. 我尝试使用has_and_belongs_to_many关联对此进行建模 class User ActiveRecord::Base has_and_belongs_to_many :followers,class_name: "User",foreign_key: "followee_id",join_table: "follo
在我的应用程序中,用户可以关注许多用户,并且可以跟随许多用户.
我尝试使用has_and_belongs_to_many关联对此进行建模 class User < ActiveRecord::Base has_and_belongs_to_many :followers,class_name: "User",foreign_key: "followee_id",join_table: "followees_followers" has_and_belongs_to_many :followees,foreign_key: "follower_id",join_table: "followees_followers" end 另外,我为连接表创建了一个迁移,如下所示: class FolloweesFollowers < ActiveRecord::Migration def up create_table 'followees_followers',:id => false do |t| t.column :followee_id,:integer t.column :follower_id,:integer end end def down drop_table 'followees_followers' end end 当我尝试访问用户的关注者(User.first.followers)时,它会抛出一个错误: SQLException: no such column: followees_followers.user_id: SELECT "users".* FROM "users" INNER JOIN "followees_followers" ON "users"."id" = "followees_followers"."user_id" WHERE "followees_followers"."followee_id" = 1 我不明白为什么要访问followees_followers.user_id.我错过了什么吗? 解决方法
设置多对多自联接时,:foreign_key和
:association_foreign_key选项很有用.
class User < ActiveRecord::Base has_and_belongs_to_many :followers,join_table: "followees_followers",association_foreign_key: "follower_id" has_and_belongs_to_many :followees,association_foreign_key: "followee_id" end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |