【问题标题】:Has many through relationship in rails在rails中有很多直通关系
【发布时间】:2014-11-07 05:02:45
【问题描述】:

我正在使用 facebook api 从 fb 获取用户。

我想将用户存储在我的模型User

我正在使用has many through 关系来存储用户

我在user 模型中的用户模型关系。

has_many :friends, :through => :user_friends, :class_name => "User", :foreign_key => "friend_id"

User friends模型中间表获取用户好友。

belongs_to :user
belongs_to :user, :foreign_key => "friend_id"

用户朋友有user_idfriend_id 列,我在迁移中添加了这些列。

在用户对象上使用 .friends 时出现错误。

ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :user_friends in model User

有人可以帮忙吗? 提前致谢。

【问题讨论】:

  • 用户和好友之间是否存在多对多关系?
  • @RichaSinha :是的,就像我们在社交网络中一样。

标签: ruby-on-rails associations has-many model-associations


【解决方案1】:

您需要查看Self-Referential Association。显然你错过了一些概念。您不能在单个模型中添加 2 个具有相同名称的关联,(只有其中一个会响应)。

您应该添加has_many :user_friends,但您仍然会缺少关联的另一端,请查看此示例:


# user.rb
has_many :user_friends
has_many :friends, :through => :user_friends
has_many :inverse_friendships, :class_name => "UserFriend", :foreign_key => "friend_id"
has_many :inverse_friends, :through => :inverse_friendships, :source => :user

# user_friends.rb
belongs_to :user
belongs_to :friend, :class_name => "User"

【讨论】:

  • :非常感谢,基本上我错过了has_many :user_friends。和型号名称我应该在第二个关联中使用friend
【解决方案2】:

has_many :through 行之前添加has_many :user_friends

【讨论】:

    【解决方案3】:

    试试这个:

    用户模型:

    has_many :user_friends
    has_many :friends, :through => :user_friends, :class_name => "User", :foreign_key => "friend_id"
    

    好友模型:

      has_many :user_friends
      has_many :users, through: :user_friends
    

    用户好友模型

      belongs_to :user
      belongs_to :friend, :foreign_key => "friend_id"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-29
      • 1970-01-01
      • 2013-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-11
      • 2023-03-11
      相关资源
      最近更新 更多