代码之家  ›  专栏  ›  技术社区  ›  Carl Edwards monkbroc

从用户订阅的板检索所有帖子

  •  0
  • Carl Edwards monkbroc  · 技术社区  · 6 年前

    class User < ApplicationRecord
      has_many :subscriptions, dependent: :destroy
      has_many :boards, through: :subscriptions
    end
    
    class Subscription < ApplicationRecord
      belongs_to :user
      belongs_to :board
    end
    
    class Board < ApplicationRecord
      has_many :subscriptions, dependent: :destroy
      has_many :subscribers, through: :subscriptions, source: :user
    end
    
    class Post < ApplicationRecord
      belongs_to :board
      belongs_to :user
    end
    

    到了展示帖子的时候,就正确的方法而言,我遇到了问题。简单的解决方案是在用户模型中设置另一个HMT关联吗?

    has_many :subscribed_posts, through: :boards, source: :posts
    

    在我的方法中我看到的一个直接缺陷是,用户会让他们的帖子显示出来,包括其他用户的帖子。更好的解决方案是创建某种SQL查询吗?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Mahmoud Sayed    6 年前

    是的,您可以构建另一个关联来检索所需的帖子,但是正如您所提到的,这也会返回用户的帖子,因此您必须设置一些条件来防止此类行为。

    has_many :subscribed_posts, through: :boards, source: :posts, conditions: {["user_id != ?", id] }