用户可以通过FollowRelationship跟踪其他用户
我希望能够说
User.first.followings
并返回用户列表
这不起作用:
Class User
has_many :following_relationships
has_many :followings, through: :following_relationships, foreign_key: :following_id, source: :user
end
Class FollowingRelationship
attr_accessible :following_id, :follower_id
belongs_to :followings, class_name: "User"
end
User.first.followings
在控制台中给出了这个:
SELECT "users".* FROM "users" INNER JOIN "following_relationships" ON "users"."id" = "following_relationships"."user_id" WHERE "following_relationships"."user_id" = 1
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: following_relationships.user_id: SELECT "users".* FROM "users" INNER JOIN "following_relationships" ON "users"."id" = "following_relationships"."user_id" WHERE "following_relationships"."user_id" = 1
有人看到我遗失的那件作品吗?
答案 0 :(得分:2)
我认为问题是FollowingRelationship
模型与User
没有任何关系
它应该有belongs_to :user
,因为您指定source: :user
,不应该吗?
我不太了解你的模型和它们之间的关系,但belongs_to :followings
看起来很奇怪
belongs_to
使用单数形式,因为它不能属于多个对象。
更新1
更清楚。
我想你应该有
class FollowingRelationship
…
belongs_to :user
belongs_to :follower
end
这意味着followings_relationships
表应包含user_id
和follower_id
列。
更新2
经过一番对话,我们已经弄明白了。
这是您应该拥有的代码
class User < ActiveRecord::Base
has_many :fade_relationships, foreign_key: :faded_id
has_many :fadings, through: :fade_relationships, source: :fading
end
class FadeRelationship < ActiveRecord::Base
attr_accessible :faded_id, :fading_id
belongs_to :fading, class_name: "User"
end