rails store array in database

# Assume you have a Rails model named 'Product' with a column named 'features' to store an array

class Product < ApplicationRecord
  serialize :features, Array
end
  1. Create a migration to add the 'features' column to the 'products' table:
rails generate migration AddFeaturesToProducts features:text
  1. Run the migration to update the database schema:
rails db:migrate
  1. Now, within your application, you can assign an array to the 'features' attribute of a 'Product' instance:
product = Product.new
product.features = ['Feature 1', 'Feature 2', 'Feature 3']
product.save
  1. Retrieve the 'features' array from a 'Product' instance:
product = Product.find(id)
features_array = product.features
  1. Update the 'features' array for a 'Product' instance:
product = Product.find(id)
product.features << 'New Feature'
product.save
  1. Query products based on a specific feature using ActiveRecord:
products_with_feature = Product.where("features @> ARRAY[?]::varchar[]", ['Feature 1'])
  1. Remove a specific element from the 'features' array of a 'Product' instance:
product = Product.find(id)
product.features.delete('Feature 2')
product.save
  1. Clear all elements from the 'features' array of a 'Product' instance:
product = Product.find(id)
product.features = []
product.save

Remember to replace 'Product' with the actual name of your model and adjust the variable names and IDs according to your application's context.