Rails 协会变得难以理解

Rails association getting complex to understand

我有点老了,但对 Rails 还是个新手,在我的学习过程中,我陷入了一个无法弄清楚如何在两个实体之间建立关联的地步。

So here is the background of app. There is a user and ad entity. User can create many ads and an ad belongs to one user so its a pretty straightforward association of one to many. Now the confusion is that I want to add a feature where users can add ads to his favorities. So one user can have multiple fav_ads and one ad has multiple likers. Its also straight forward many to many association but there is already has many ads in user model so if I even user has many ads through fav_ads where fav_ads is a bridge table and vise versa then user.ads will give me what? I now there must a way fir this scenario as its pretty common in webapps and database but don't know how to do it in rails.

您需要一个联接 table,其中一列用于 user_id,一列用于 ad_id。 这个 table 可能被称为“user_ad_like”。

对于您使用 create_join_table 的迁移(docs)

类似

class UserAdLike < ActiveRecord::Migration[6.0]
  def change
    create_join_table(:users, :ads, table_name: "user_ad_like"
  end
end

对于您将使用的模型 has_and_belongs_to_many (docs)

class Ad
    # Likes  (ad.likers)
    has_and_belongs_to_many :likers, class_name: 'User', join_table: "user_ad_like"
    # Creator (ad.user)
    belongs_to :user
end
class User
    # Liked ads (user.liked_ads)
    has_and_belongs_to_many :liked_ads, class_name: 'Ad', join_table: "user_ad_like"
    # Ads create (user.ads)
    has_many :ads
end

然后您将拥有

  1. user.ads 为您制作的广告
  2. user.liked_ads 给你喜欢的广告
  3. ad.person 这给了你创造者
  4. ad.likers 这会为您提供所有喜欢该广告的用户。