Ix Techau
Ix Techau

Reputation: 71

Include array when creating a model

I have a discussion forum where users can see a list of unread posts. The way I'm doing this is to use a Look, User and Post model:

class Look < ActiveRecord::Base
  belongs_to :post
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :posts, through: :looks
  has_many :looks
end

class Post < ActiveRecord::Base
  belongs_to :user
  has_many :looks
  has_many :users, through: :looks
end

So the way this works is that there is a list of all post IDs a user has viewed. It's created through the 'show' method:

def show
  if current_user
    viewer = current_user
    view_ids = viewer.posts.pluck(:id).uniq
    not_viewed = Post.where("id not in (?)", view_ids)
    not_viewed_ids = not_viewed.pluck(:id)

    unless Post.find(params[:id]).in?(not_viewed_ids)
      Look.create(user: current_user, post: @post, viewstamp: Time.now)
    end
  end
end

This all works fine so far. The problem is I want to create a Look for all posts, so that I can essentially 'mark all as read'. This line works fine for creating a Look for the current post:

unless Post.find(params[:id]).in?(not_viewed_ids)
  Look.create(user: current_user, post: @post, viewstamp: Time.now)
end

...but how do I make one that creates a Look for every post? Like this:

Look.create(user: current_user, post: [NEED ARRAY OF POSTS HERE], viewstamp: Time.now)

The reason I want to do this is so a user can mark all posts as read.

Upvotes: 0

Views: 22

Answers (1)

SteveTurczyn
SteveTurczyn

Reputation: 36860

You can create the Look automatically just by adding the users to the posts.

Post.all.each { |p| p.users << current_user; p.save }

Upvotes: 1

Related Questions