gpt4 book ai didi

ruby-on-rails - Ruby on Rails 与 self 的多对多关系

转载 作者:搜寻专家 更新时间:2023-10-30 22:15:01 27 4
gpt4 key购买 nike

我正在尝试将一个人的 Facebook 好友保存到我的数据库中。我想将 Facebook 用户存储在一个表中,然后将他们的友谊存储在另一个表中。友谊将具有请求友谊的 FacebookUser 的整数和 friend 的整数,两者都是 facebook_users 表的外键。但是,当我尝试将用户的 Facebook 好友链接到好友时,我不断收到此消息。

错误

ActiveRecord::HasManyThroughSourceAssociationNotFoundError: Could not find the source association(s) :friend or :friends in model Friendship. Try 'has_many :friends, :through => :friendships, :source 
=> <name>'. Is it one of :FacebookUser or :FacebookFriend?

友谊.rb

class Friendship < ActiveRecord::Base
attr_accessible :facebook_user_id, :facebook_friend_id

belongs_to :FacebookUser
belongs_to :FacebookFriend, :class_name => :FacebookUser
end

facebook_user.rb

class FacebookUser < ActiveRecord::Base
attr_accessible :first_name, :gender, :last_name

has_many :friendships, :foreign_key => :facebook_user_id
has_many :friends, :through => :friendships, :source => :FacebookUser
end

架构

create_table "facebook_users", :force => true do |t|
t.string "first_name"
t.string "last_name"
t.string "gender"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end

create_table "friendships", :force => true do |t|
t.integer "facebook_user_id"
t.integer "facebook_friend_id"
end

最佳答案

Rails 使用的约定是使用由类名和外键定义的关联。如果您像上面那样设置了表格,则应将模型更改为以下内容。

class Friendship < ActiveRecord::Base
attr_accessible :facebook_user_id, :facebook_friend_id

belongs_to :facebook_user # implies a foreign key of facebook_user_id and class of FacebookUser
belongs_to :facebook_friend, class_name: 'FacebookUser' #implies a foreign key of facebook_friend_id
end

class FacebookUser < ActiveRecord::Base
attr_accessible :first_name, :gender, :last_name

has_many :friendships
has_many :friends, :through => :friendships, :source => :facebook_friend
end

关于ruby-on-rails - Ruby on Rails 与 self 的多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14994819/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com