Tim Yip
Tim Yip

Reputation: 123

Rails: controller that lets teacher only see posts his students make

Currently I have a teacher controller that lets the teacher see all student posts.

def index
  if params[:user_id]
    @posts = Post.where(user_id: params[:user_id])
  else
    @posts = Post.all
  end
end

How would you let teachers see posts of their students only, and not posts made by students who have a different teacher? I am using devise.

This is what I have for the teacher controller:

class TeachersController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]


def index
  if params[:user_id]
   @posts = Post.where(user_id: params[:user_id])
 else
    @posts = Post.all
  end

end

end

Upvotes: 0

Views: 100

Answers (1)

Brent Eicher
Brent Eicher

Reputation: 1050

Without having any information about your associations or authentication, I'll answer by making the following assumptions:

  1. A post belongs_to a student, a student has_many posts
  2. A student belongs_to a teacher, a teacher has_many students
  3. The teacher is the current user

The most simple way to limit posts to a teacher is by defining an additional ActiveRecord association. In the Teacher class, you might add:

has_many :student_posts, through: :students, source: :posts

In your controller, you can do something like:

class TeacherController

  before_action :find_teacher, only: [:index]

  def index
    @posts = @teacher.student_posts
  end

  private

  def find_teacher
    @teacher = current_user
  end 
end

ActiveRecord will only return posts that belong to students that belong to a given teacher. Note that this is a concept illustration and not meant to by copy and pasted.

Upvotes: 1

Related Questions