【问题标题】:Following implementation实施后
【发布时间】:2021-01-15 09:36:09
【问题描述】:

我有一个用户模型和一个商店模型。我想设置模型关联,以便用户能够关注商店。这意味着用户将成为关注者,商店将成为关注者。

为此我创建了一个跟随模型,并添加了与其他模型的关联:

class CreateFollows < ActiveRecord::Migration[6.0]
  def change
    create_table :follows do |t|
      t.integer :store_id
      t.integer :user_id
      t.string :uid

      t.timestamps
    end
  end
end

class Follow < ApplicationRecord
  belongs_to :store
  belongs_to :user
end

class User < ApplicationRecord
  has_many :follows
end

它工作正常,但我很确定这不是正确的设置。我也找到了这个tutorial,但我不知道如何在我的情况下使用它。关于如何正确设置模型关联的任何想法?提前致谢!

【问题讨论】:

  • 用户应该关注多个商店还是只关注一个?
  • 感谢@borjagvo 的回复。是的,这是正确的,用户将能够关注多个商店。

标签: ruby-on-rails ruby-on-rails-5


【解决方案1】:

你基本上已经明白了。

您缺少的是让用户看到他们关注的商店,反之亦然。使用has_many :through 进行操作。

class User < ApplicationRecord
  has_many :follows
  has_many :stores, through: :follows
end

class Store < ApplicationRecord
  has_many :follows
  has_many :users, through: :follows
end

现在user.stores 将获取用户关注的商店,store.users 将获取哪些用户关注该商店。它将为您处理连接并缓存结果。

【讨论】:

  • 感谢@Schwern 的回复。我有点觉得少了点什么。我会试一试,我会告诉你的! :))))))
  • 嘿@Schwern,我测试了它,它工作得很好!不过,我还有一个问题,有没有一种方法可以让我也获得当前用户的个人关注……像 current_user.store 这样的东西?
  • @Theopap 不,因为用户正在关注许多商店。用户没有关注任何一家商店。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-19
  • 2013-02-01
  • 1970-01-01
相关资源
最近更新 更多