gpt4 book ai didi

ruby-on-rails - 你如何在 rails 中为 "Likes"建模?

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

我有 3 个模型:用户、对象、喜欢

目前,我有模型:一个用户有很多对象。我如何进行建模:

1) 一个用户可以喜欢很多对象

2) 一个对象可以有很多点赞(来自不同的用户)

所以我希望能够做这样的事情:

User.likes = 用户喜欢的对象列表

Objects.liked_by = 对象喜欢的用户列表

下面的模型肯定是错误的...

class User < ActiveRecord::Base
has_many :objects
has_many :objects, :through => :likes
end

class Likes < ActiveRecord::Base
belongs_to :user
belongs_to :object
end

class Objects < ActiveRecord::Base
belongs_to :users
has_many :users, :through => :likes
end

最佳答案

为了进一步阐述我对 Brandon Tilley 的回答的评论,我建议如下:

class User < ActiveRecord::Base
# your original association
has_many :things

# the like associations
has_many :likes
has_many :liked_things, :through => :likes, :source => :thing
end

class Like < ActiveRecord::Base
belongs_to :user
belongs_to :thing
end

class Thing < ActiveRecord::Base
# your original association
belongs_to :user

# the like associations
has_many :likes
has_many :liking_users, :through => :likes, :source => :user
end

关于ruby-on-rails - 你如何在 rails 中为 "Likes"建模?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11945487/

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