1

I have these models:

class Account < ApplicationRecord
  has_many :account_members, dependent: :destroy
  has_many :users, through: :account_members
  has_many :projects, dependent: :destroy

end

and

class Project < ApplicationRecord
  belongs_to :account
  has_many :project_members, dependent: :destroy
end

and

class ProjectMember < ApplicationRecord
  belongs_to :project
  belongs_to :account_member
end

and

class AccountMember < ApplicationRecord
  belongs_to :account
  belongs_to :user
  has_many :project_members, dependent: :destroy
end

My account's controller index function

  def index
    @accounts = @current_user.accounts

    render json: @accounts, include: params[:include]
  end

The problem is this action returns the accounts with all projects BUT the user might only be a member of 2 projects. I want it to return only projects that the user has access to through the project_members relationship.

How do you do that?

EDIT 1 I am also using cancancan if that makes a difference.

EDIT 2 This is the account serializer

class AccountSerializer < ActiveModel::Serializer
  attributes :id, :name
  has_many :users
  has_many :account_members
  has_many :invites
  has_many :projects
  has_many :clients
end
1
  • I am also using cancancan if that makes a difference. Commented Oct 19, 2017 at 19:16

1 Answer 1

2

As you use cancancan you can filter it through ability in AccountSerializer

has_many :projects do
  ability = Ability.new(scope)
  @object.projects.select{ |p| ability.can?(:read, p) }
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.