【问题标题】:Ruby on Rails - Joins models for getting notificationsRuby on Rails - 加入模型以获取通知
【发布时间】:2018-01-28 14:06:20
【问题描述】:

在我的应用程序中,我有模型 UserPostNotificationPostShareSocialPage

这就是我的模型关联方式:

class User < ActiveRecord::Base
  has_many :social_pages
  has_many :posts


class Post < ActiveRecord::Base
  has_many :post_shares
  has_many :notifications
  belongs_to :user


class Notification < ActiveRecord::Base
  belongs_to :post


class PostShare < ActiveRecord::Base
  belongs_to :post
  belongs_to :social_page


class SocialPage < ActiveRecord::Base
  belongs_to :user
  has_many :post_shares

当添加notifications 时,我会将post_id 添加到我的表中。

我想要实现的是,基于来自notificationspost_id,我想为那个post_id 找到post_shares 并找到social_pages_id 和基于social_page_id 的用户有拥有/创建页面并向他们显示通知。

我已经尝试过使用joins,比如Notification.joins(:post).group(:post_id).select(:post_id),但我没有得到任何正确的结果。

感谢任何帮助!

【问题讨论】:

    标签: ruby ruby-on-rails-4 join model controller


    【解决方案1】:

    ActiveRecord 上的 Rails 嵌套包含或嵌套连接将在这里解决您的问题

    Rails - Nested includes on Active Records?

    你可以这样做

    notifications = Notification.includes(post: [:user, post_shares: [social_page: :user]]).where(post_id: your_post_id)
    

    notifications = Notification.joins(post: [post_shares: [social_page: :user]]).where(post_id: your_post_id)
    

    然后您可以像这样访问帖子和社交页面用户

    post_user = notifications.map(&:post).map(&:user)
    
    post_shares = []
    notifications.each do |n|
      post_shares += n.post.post_shares
    end
    
    social_page_users = post_shares.map(&:social_page).map(&:user)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-23
      • 2011-11-04
      • 2021-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多