【发布时间】:2019-02-11 23:36:42
【问题描述】:
我正在建立用户之间的匹配系统,最初它有并且属于许多关联,但是由于我需要该连接表的一些验证和其他数据,我需要有那个模型,并将其更改为有许多通过。
has_and_belongs_to_many(:likes,
class_name: :User,
join_table: :user_likes,
foreign_key: :user_liker_id,
association_foreign_key: :user_liked_id)
has_and_belongs_to_many(:likeds,
class_name: :User,
join_table: :user_likes,
foreign_key: :user_liked_id,
association_foreign_key: :user_liker_id)
这是旧的实现,需要通过转换为 has_many。如您所见,通过这个我可以检索我喜欢的所有用户和喜欢我的用户。我已经创建了UserLike 模型,但我没有成功使它在用户模型中可用。我已经尝试过的是:
用户.rb
has_many :user_likes
has_many :likes, through: :user_likes, foreign_key: :user_liked_id
has_many :likeds, through: :user_likes, foreign_key: :user_liker_id
user_like.rb
class UserLike < ApplicationRecord
belongs_to :user
end
此实现引发以下异常:
ActiveRecord::HasManyThroughSourceAssociationNotFoundError: 在模型 UserLike 中找不到源关联“like”或 :likes。尝试 'has_many :likes, :through => :user_likes, :source => '。是 user 还是 user_likes 之一?
我不知道我在这里缺少什么,任何帮助将不胜感激:)
【问题讨论】:
-
尝试为两个关联指定
class_name: 'User'
标签: ruby-on-rails ruby rails-activerecord