Strong Parameters – Restricting Collection

Recently I was trying to find a way for strong parameters to restrict a collection to the items a user owns but I could not find anything so I decided to do something myself.

I want a Category to accept an array of member_ids but I want them to be only the members the user owns (preventing a user from assigning someone else’s members).

In the controller we expose the members and the category and only use the organization’s members:


class CategoriesController < ApplicationController
  expose(:organization)

  expose(:members) { organization.members }

  expose(:category, attributes: :category_params)

  def new
  end

  def create
    category.members &= members
    
    if category.save
      redirect_to category_path
    else
      render :new
    end
  end

private

  def category_params
    params.require(:category).permit(:name, {:member_ids => []})
  end
end

And now the category will only contain members that the organization (or user) owns. It may not be the most efficient way of doing this so if you have any suggestions please leave a comment.

Leave a Reply