gpt4 book ai didi

ruby-on-rails - 类似 Twitter 关注者/在 ActiveRecord 中关注的关系

转载 作者:数据小太阳 更新时间:2023-10-29 06:37:24 25 4
gpt4 key购买 nike

我试图在我的应用程序中表示用户之间的关系,其中一个用户可以有很多关注者并且可以关注其他用户。我想要像 user.followers() 和 user.followed_by() 这样的东西你能详细告诉我如何使用 ActiveRecord 表示这个吗?

谢谢。

最佳答案

你需要两个模型,一个 Person 和一个 Followings

rails generate model Person name:string
rails generate model Followings person_id:integer follower_id:integer blocked:boolean

以及模型中的以下代码

class Person < ActiveRecord::Base
has_many :followers, :class_name => 'Followings', :foreign_key => 'person_id'
has_many :following, :class_name => 'Followings', :foreign_key => 'follower_id'
end

和你写的Followings类中对应

class Followings < ActiveRecord::Base
belongs_to :person
belongs_to :follower, :class_name => 'Person'
end

您可以根据自己的喜好使名称更清晰(我特别不喜欢 Followings-name),但这应该让您入门。

关于ruby-on-rails - 类似 Twitter 关注者/在 ActiveRecord 中关注的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3397920/

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