Rails通过关系自我加入has_many

时间:2016-08-27 17:46:08

标签: ruby-on-rails activerecord

用户可以通过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

有人看到我遗失的那件作品吗?

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_idfollower_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