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
- Create a migration to add the 'features' column to the 'products' table:
rails generate migration AddFeaturesToProducts features:text
- Run the migration to update the database schema:
rails db:migrate
- 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
- Retrieve the 'features' array from a 'Product' instance:
product = Product.find(id)
features_array = product.features
- Update the 'features' array for a 'Product' instance:
product = Product.find(id)
product.features << 'New Feature'
product.save
- Query products based on a specific feature using ActiveRecord:
products_with_feature = Product.where("features @> ARRAY[?]::varchar[]", ['Feature 1'])
- Remove a specific element from the 'features' array of a 'Product' instance:
product = Product.find(id)
product.features.delete('Feature 2')
product.save
- 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.