user7383466
user7383466

Reputation:

Ruby on Rails - Joins models for getting notifications

In my application I have models User, Post, Notification, PostShare & SocialPage.

This is how I've my models associations:

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

When notifications are added, I'm adding post_id to my table.

What I want to achieve is, based on the post_id from notifications, I want to find post_shares for that post_id & find the social_pages_id & based social_page_id find which user has own/created the page and show them notifications.

I've tried with joins like Notification.joins(:post).group(:post_id).select(:post_id), but I don't get anything correct.

Any help is appreciated!

Upvotes: 0

Views: 46

Answers (1)

Rohit Kumar
Rohit Kumar

Reputation: 71

Rails nested includes or nested joins on ActiveRecord will solve your problem here

Rails - Nested includes on Active Records?

You can do something like this

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

OR

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

And then you can access post & social page users like this

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)

Upvotes: 1

Related Questions