Ruby on Rails 7: Validate collection_check_boxes array

44 Views Asked by At

In Rails, I have a model called Post with a field called columns. The user can select which columns are to be displayed. I do this using the following line of code in my form:

<%= form.collection_check_boxes(:columns, { "Title": "title", "Body": "body" }, :last, :first) %>

I use this so that I can simply store the columns the user wants to display in an array in my database. The problem is that I need to validate this array to make sure that only the allowed columns can be selected. To do this, I have the following validation for my post model:

validate :validate_columns

def validate_columns
  permitted = [ "title", "body" ]

  unless columns.is_a?(Array) && columns.all?{ |c| permitted.include?(c) }
    errors.add(:columns, :invalid)
  end
end

This works well for only allowing the wanted columns, however now I cannot submit the form without getting an error since the collection_check_boxes helper automatically adds an empty field to the array to handle the case when no checkboxes are selected. The problem is that this fails my validation.

I have already read about the include_hidden: false option for collection_check_boxes, however if I use that, the user cannot deselect all columns.

So, does anybody have any ideas on how I could solve this or if this approach is even viable at all?

Edit:

These are my strong params in my controller:

def post_params
  params.require(:post).permit(:title, :body, columns: [])
end

And this is my migration:

def change
  create_table :posts do |t|
    t.string :title
    t.text :body
    t.string :columns, array: true, default: []

    t.timestamps
  end
end
0

There are 0 best solutions below