Activerecord asociation无法在朋友系统

时间:2018-04-13 09:37:16

标签: ruby-on-rails activerecord

我试图测试一个Facebook风格的朋友系统。我有一个简单的用户模型和一个UserRelationship模型,它从用户表中获取两个外键,我将其命名为inviter_idinvited_id

class User < ApplicationRecord
  has_many :user_relationships
  has_many :friends, through: :user_relationships, source: :invited
end

class UserRelationship < ApplicationRecord
  belongs_to :inviter, class_name: "User"
  belongs_to :invited, class_name: "User"
end

我尝试过各种变化,但我无法弄清楚我哪里出错了。我希望能够拨打User.first.friends并获得完整的朋友列表。目前我得到的错误是:

ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column user_relationships.user_id does not exist

表格:

create_table "user_relationships", force: :cascade do |t|
  t.integer  "inviter_id"
  t.integer  "invited_id"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

create_table "users", force: :cascade do |t|
  t.string   "name"
  t.string   "email"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

由于

更新

使用Abhilash所说的关于has_many :user_relationships关联的内容,我将其更改为:

class User < ApplicationRecord
  has_many :user_relationships, foreign_key: "invited_id"
  has_many :friends, through: :user_relationships, source: :invited
end

问题是只返回邀请,而不是邀请者。我觉得应该有办法同时使用数据库和关联吗?

1 个答案:

答案 0 :(得分:1)

您需要从User模型中删除以下行。

has_many :user_relationships

因为在UserRelationship模型中您有inviter_idinvited_id但不是user_id的字段。

因此,您可以在模型中使用这样的方法来获取给定用户的user_relationships

def user_relationships
    UserRelationship.where("invited_id = ? OR inviter_id = ?", self.id, self.id)
end

编辑:

您还可以拥有以下关联:

class User < ActiveRecord::Base
  has_many :inviter_user_relationships, :class_name => 'UserRelationship', :foreign_key => 'inviter_id'
  has_many :invited_user_relationships, :class_name => 'UserRelationship', :foreign_key => 'invited_id'

  def user_relationships
    inviter_user_relationships + invited_user_relationships
  end

end