### Install Docker and Dependencies via Homebrew Source: https://github.com/algolia/algoliasearch-rails/blob/master/DOCKER_README.MD Commands to install Docker, Docker Machine, and VirtualBox on macOS using Homebrew. These tools provide the necessary infrastructure to run the project's Docker containers. ```bash brew install docker brew install docker-machine brew cask install virtualbox ``` -------------------------------- ### Install Algolia Search Gem for Rails Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Installs the algoliasearch-rails gem. Add it to your Gemfile and run bundle install. ```shell gem install algoliasearch-rails bundle install ``` ```ruby gem "algoliasearch-rails" ``` -------------------------------- ### Configure Docker Machine Source: https://github.com/algolia/algoliasearch-rails/blob/master/DOCKER_README.MD Initializes a new Docker machine using the VirtualBox driver and configures the current shell environment to communicate with the new machine. ```bash docker-machine create --driver virtualbox default docker-machine env default eval "$(docker-machine env default)" ``` -------------------------------- ### Build and Run Docker Container Source: https://github.com/algolia/algoliasearch-rails/blob/master/DOCKER_README.MD Instructions for building the Docker image and running it with necessary environment variables. The container mounts the current directory to /app for real-time development. ```bash docker build -t algolia-rails . docker run -it --rm --env ALGOLIA_APPLICATION_ID --env ALGOLIA_API_KEY -v $PWD:/app -w /app algolia-rails bash ``` -------------------------------- ### Execute Test Suite Source: https://github.com/algolia/algoliasearch-rails/blob/master/DOCKER_README.MD Commands to run the RSpec test suite within the Docker container. Supports running the entire suite or specific test files. ```bash bundle exec rspec bundle exec rspec ./path/to/test_spec.rb:#line_number ``` -------------------------------- ### Advanced AlgoliaSearch Model Configuration Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md A comprehensive example of configuring searchable attributes, custom ranking, tags, and separators in an ActiveRecord model. ```ruby class Item < ActiveRecord::Base include AlgoliaSearch algoliasearch per_environment: true do attribute :created_at, :title, :url, :author, :points, :story_text, :comment_text, :author, :num_comments, :story_id, :story_title attribute :created_at_i do created_at.to_i end searchableAttributes ['unordered(title)', 'unordered(story_text)', 'unordered(comment_text)', 'unordered(url)', 'author'] tags do [item_type, "author_#{author}", "story_#{story_id}"] end customRanking ['desc(points)', 'desc(num_comments)'] separatorsToIndex '+#$' end end ``` -------------------------------- ### Configure Algolia Pagination Backend in Rails Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Sets the pagination backend for Algolia search results in a Rails application. This example configures the backend to use the `will_paginate` gem. ```ruby AlgoliaSearch.configuration = { application_id: 'YourApplicationID', api_key: 'YourAPIKey', pagination_backend: :will_paginate } ``` -------------------------------- ### Configure AlgoliaSearch for Sequel ORM Source: https://context7.com/algolia/algoliasearch-rails/llms.txt Provides an example of using the AlgoliaSearch DSL within a Sequel model, including the use of the touch plugin to maintain data consistency. ```ruby class SequelBook < Sequel::Model plugin :active_model include AlgoliaSearch algoliasearch synchronous: true, per_environment: true do attributes :name, :author add_attribute :formatted_title do "#{name} by #{author}" end searchableAttributes ['name', 'author'] end end class Author < Sequel::Model one_to_many :books plugin :timestamps plugin :touch def touch super books.each(&:touch) end end ``` -------------------------------- ### Direct Client Search Execution Source: https://github.com/algolia/algoliasearch-rails/blob/master/UPGRADING_TO_V3.MD Since the Index object has been removed, developers must now use the AlgoliaSearch client directly to perform searches. Pass the index name to the client's search method. ```ruby # Before res = Product.index.search('shoe') # After res = AlgoliaSearch.client.search_single_index(Product.index_name, { query: 'shoe' }) ``` -------------------------------- ### Target multiple indices for a single model Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Uses the add_index method to sync records across multiple indices based on conditional logic. Includes examples for searching against these extra indices. ```ruby class Book < ActiveRecord::Base include AlgoliaSearch algoliasearch index_name: "Book_#{Rails.env}" do add_index "SecuredBook_#{Rails.env}", if: :public? do; end end end # Searching Book.search 'foo bar', index: 'Book_by_editor' ``` -------------------------------- ### Retrieving Replica Index Names Source: https://github.com/algolia/algoliasearch-rails/blob/master/UPGRADING_TO_V3.MD The index_name method now accepts an optional parameter to retrieve the name of a replica index. This ensures configuration options like per_environment are correctly applied to the generated name. ```ruby def Product include AlgoliaSearch algoliasearch({ per_environment: true }) do add_replica 'Suits', per_environment: true do # replica settings end end end main_index_name = Product.index_name replica_index_name = Product.index_name('Suits') ``` -------------------------------- ### Accessing Search Results with Symbol Keys Source: https://github.com/algolia/algoliasearch-rails/blob/master/UPGRADING_TO_V3.MD In version 3, search result response keys are returned as symbols instead of strings. Developers must update code to access hash values using symbol keys. ```ruby # Before results = Product.raw_search('shirt') p results['hits'] # After results = Product.raw_search('shirt') p results[:hits] ``` -------------------------------- ### Handling Facet Values as Objects Source: https://github.com/algolia/algoliasearch-rails/blob/master/UPGRADING_TO_V3.MD The search_for_facet_values method now returns objects of type Algolia::Search::FacetHits instead of raw hashes. Accessing facet data requires using method calls instead of hash key lookups. ```ruby # Before facets = Color.search_for_facet_values('short_name', 'bl', :query => 'black') puts facets.first['value'] # After facets = Color.search_for_facet_values('short_name', 'bl', :query => 'black') facets.first.value ``` -------------------------------- ### Configure Background Queues for Indexing Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Explains how to offload indexing tasks to background workers using ActiveJob, Sidekiq, or DelayedJob to prevent blocking the main thread. ```ruby # ActiveJob example class Contact < ActiveRecord::Base include AlgoliaSearch algoliasearch enqueue: true do attribute :first_name, :last_name, :email end end # Sidekiq integration class Contact < ActiveRecord::Base include AlgoliaSearch algoliasearch enqueue: :trigger_sidekiq_worker do attribute :first_name, :last_name, :email end def self.trigger_sidekiq_worker(record, remove) MySidekiqWorker.perform_async(record.id, remove) end end ``` -------------------------------- ### Search using replica indices Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Demonstrates how to perform a search query against a specific replica index using the raw_search or search methods. ```ruby Book.raw_search 'foo bar', replica: 'Book_by_editor' # or Book.search 'foo bar', replica: 'Book_by_editor' ``` -------------------------------- ### Configure AlgoliaSearch Client Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Initializes the AlgoliaSearch configuration with application credentials. This should be performed during the Rails application initialization process. ```ruby AlgoliaSearch.configuration = { application_id: 'YourApplicationID', api_key: 'YourAPIKey', } ``` -------------------------------- ### Configure Algolia Credentials in Rails Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Sets up your Algolia Application ID and API Key in a Rails initializer. Ensure you replace 'YourApplicationID' and 'YourAPIKey' with your actual credentials. ```ruby AlgoliaSearch.configuration = { application_id: 'YourApplicationID', api_key: 'YourAPIKey' } ``` -------------------------------- ### Implement Frontend Search with JavaScript Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Demonstrates how to perform search queries directly from the client-side using the Algolia JavaScript API client. This approach reduces server latency and offloads processing from the Rails backend. ```javascript var client = algoliasearch(ApplicationID, Search-Only-API-Key); var index = client.initIndex('YourIndexName'); index.search('something', { hitsPerPage: 10, page: 0 }) .then(function searchDone(content) { console.log(content) }) .catch(function searchFailure(err) { console.error(err); }); ``` -------------------------------- ### Perform Dynamic Search with Parameters in Rails Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Shows how to execute a search query with dynamic search parameters, such as `hitsPerPage` and `page`, passed as the second argument to the `raw_search` method. ```ruby # dynamical search parameters p Contact.raw_search('jon doe', { hitsPerPage: 5, page: 2 }) ``` -------------------------------- ### Configure Algolia Connection in Rails Source: https://context7.com/algolia/algoliasearch-rails/llms.txt Initializes the Algolia Search Rails gem by setting your application credentials and optionally specifying the pagination backend. ```ruby # config/initializers/algoliasearch.rb AlgoliaSearch.configuration = { application_id: 'YourApplicationID', api_key: 'YourAPIKey', pagination_backend: :kaminari # optional: :will_paginate, :pagy } ``` -------------------------------- ### Configuring Model Attributes and Options Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Shows how to configure AlgoliaSearch within a Rails model, including sanitization, UTF-8 encoding, and error handling settings. ```ruby class User < ActiveRecord::Base include AlgoliaSearch algoliasearch per_environment: true, sanitize: true do attributes :name, :email, :company end end gem 'rails-html-sanitizer' class User < ActiveRecord::Base include AlgoliaSearch algoliasearch force_utf8_encoding: true do attributes :name, :email, :company end end class Contact < ActiveRecord::Base include AlgoliaSearch algoliasearch raise_on_failure: Rails.env.development? do attribute :first_name, :last_name, :email end end ``` -------------------------------- ### Batch Indexing and Reindexing in AlgoliaSearch-Rails Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Demonstrates how to perform batch indexing operations and reindexing on ActiveRecord models using AlgoliaSearch. ```ruby MyModel.where('updated_at > ?', 10.minutes.ago).reindex! MyModel.index_objects MyModel.limit(5) ``` -------------------------------- ### Perform Model Indexing Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Provides methods to trigger indexing for individual models or bulk indexing for all models in the application. Requires models to be loaded before execution. ```ruby Product.reindex Rails.application.eager_load! algolia_models = ActiveRecord::Base.descendants.select{ |model| model.respond_to?(:reindex) } algolia_models.each(&:reindex) ``` -------------------------------- ### Use Paginated Search Results in Rails Views Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Illustrates how to use paginated search results in Rails views, supporting both `will_paginate` and `kaminari` gems. The `@results` variable, obtained from a search query, is passed to the pagination helper. ```ruby # in your controller @results = MyModel.search('foo', hitsPerPage: 10) # in your views # if using will_paginate <%= will_paginate @results %> # if using kaminari <%= paginate @results %> ``` -------------------------------- ### Define Search Synonyms Source: https://context7.com/algolia/algoliasearch-rails/llms.txt Configures synonym groups to improve search relevancy, allowing different terms to return the same search results. ```ruby class Product < ActiveRecord::Base include AlgoliaSearch algoliasearch do attributes :name, :description synonyms [ ['iphone', 'apple phone', 'ios device'], ['laptop', 'notebook', 'portable computer'], ['tv', 'television', 'flatscreen'] ] end end ``` -------------------------------- ### Restrict Algolia Indexing Based on Conditions (Ruby) Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Demonstrates how to conditionally index records in Algolia using the `:if` and `:unless` options within the `algoliasearch` configuration. This allows for fine-grained control over which records are included in the index. ```ruby class Post < ActiveRecord::Base include AlgoliaSearch algoliasearch if: :published?, unless: :deleted? do end def published? # [...] end def deleted? # [...] end end ``` ```ruby class Contact < ActiveRecord::Base include AlgoliaSearch algoliasearch if: :published do end def published # true or false end def published_changed? # return true only if you know that the 'published' state changed end end ``` -------------------------------- ### Manage Auto-indexing and Synchronous Operations Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Shows how to disable automatic indexing or force synchronous operations for testing purposes using configuration options. ```ruby class Contact < ActiveRecord::Base include AlgoliaSearch algoliasearch auto_index: false, auto_remove: false do attribute :first_name, :last_name, :email end end # For synchronous operations (testing only): algoliasearch synchronous: true do attribute :first_name, :last_name, :email end ``` -------------------------------- ### Configure Background Job Queuing Source: https://context7.com/algolia/algoliasearch-rails/llms.txt Offload indexing tasks to background workers using ActiveJob, Sidekiq, or DelayedJob to prevent blocking the main request cycle. ```ruby # ActiveJob algoliasearch enqueue: true do ... end # Sidekiq def self.trigger_sidekiq_worker(record, remove) ContactIndexWorker.perform_async(record.id, remove) end # DelayedJob def self.trigger_delayed_job(record, remove) remove ? record.delay.remove_from_index! : record.delay.index! end ``` -------------------------------- ### Index Nested Objects and Relations in ActiveRecord Source: https://context7.com/algolia/algoliasearch-rails/llms.txt Demonstrates how to index nested associations and flattened attributes within an ActiveRecord model. It also shows how to use the touch method to propagate changes from parent models to indexed child records. ```ruby class Profile < ActiveRecord::Base include AlgoliaSearch belongs_to :user has_many :skills algoliasearch do attributes :bio, :location attribute :user do { name: user.name, email: user.email, avatar_url: user.avatar_url } end attribute :skills do skills.map { |s| { name: s.name, level: s.level } } end add_attribute :user_name do user.name end end end class User < ApplicationRecord has_many :profiles after_save { profiles.each(&:touch) } end class Profile < ApplicationRecord belongs_to :user after_touch :index! include AlgoliaSearch algoliasearch do attribute :user do user.as_json(only: [:name, :email]) end end end ``` -------------------------------- ### Use ActiveModel Serializers for Indexing Source: https://context7.com/algolia/algoliasearch-rails/llms.txt Shows how to decouple indexing logic from models by using ActiveModel Serializers to define the structure of the indexed JSON object. ```ruby class ProductSerializer < ActiveModel::Serializer attributes :name, :formatted_price, :category_name def formatted_price "$#{object.price.to_f / 100}" end def category_name object.category.name end end class Product < ActiveRecord::Base include AlgoliaSearch belongs_to :category algoliasearch do use_serializer ProductSerializer tags do [category.name.downcase, featured? ? 'featured' : nil].compact end end end ``` -------------------------------- ### Manage Replica Indices Source: https://context7.com/algolia/algoliasearch-rails/llms.txt Create replica indices for different sorting or filtering requirements. Supports standard, inherited, and virtual replicas to optimize search performance. ```ruby class Product < ActiveRecord::Base include AlgoliaSearch algoliasearch per_environment: true do attributes :name, :price, :rating, :created_at searchableAttributes ['name'] customRanking ['desc(rating)'] add_replica 'products_price_asc', per_environment: true do customRanking ['asc(price)'] end add_replica 'products_newest', inherit: true, per_environment: true do customRanking ['desc(created_at)'] end add_replica 'products_price_desc', virtual: true do customRanking ['desc(price)'] end end end ``` -------------------------------- ### Configure Geo-Search in ActiveRecord Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Demonstrates how to enable geo-spatial search capabilities by defining latitude and longitude attributes within the algoliasearch block. ```ruby class Contact < ActiveRecord::Base include AlgoliaSearch algoliasearch do geoloc :lat_attr, :lng_attr end end ``` -------------------------------- ### Access Highlighted Search Results in Rails Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Demonstrates how to access the 'highlight_result' attribute, which is added to each ORM object returned by a search query. This allows for displaying search terms within the results. ```ruby hits[0].highlight_result['first_name']['value'] ``` -------------------------------- ### Enable Faceting and Filtering for Search Results Source: https://context7.com/algolia/algoliasearch-rails/llms.txt Configures attributes for faceting and demonstrates how to perform searches with facets and filter results based on facet values. ```ruby class Product < ActiveRecord::Base include AlgoliaSearch algoliasearch do attributes :name, :category, :brand, :price # Enable faceting on specific attributes attributesForFaceting [:category, :brand, 'searchable(name)'] end end # Search with facets results = Product.search('laptop', facets: '*') # Access facet counts results.facets['category'] # => {"Electronics" => 42, "Accessories" => 15} results.facets['brand'] # => {"Apple" => 20, "Dell" => 12, "HP" => 10} # Filter by facet values filtered = Product.search('laptop', facets: '*', filters: 'category:Electronics AND brand:Apple' ) # Search for facet values facet_hits = Product.search_for_facet_values('category', 'Elec') # => [{value: "Electronics", highlighted: "Electronics", count: 42}] ``` -------------------------------- ### Use ActiveModel Serializer with AlgoliaSearch in Rails Source: https://github.com/algolia/algoliasearch-rails/blob/master/CHANGELOG.MD This snippet demonstrates how to integrate ActiveModel Serializer with the AlgoliaSearch gem in a Rails application. It shows how to specify a custom serializer for indexing data to Algolia. No external dependencies are required beyond the gem itself. ```ruby class SerializedObject < ActiveRecord::Base include AlgoliaSearch algoliasearch do use_serializer SerializedObjectSerializer tags do ['tag1', 'tag2'] end end end ``` -------------------------------- ### Integrate Pagination Gems Source: https://context7.com/algolia/algoliasearch-rails/llms.txt Configure AlgoliaSearch to work with Kaminari, will_paginate, or Pagy for seamless result pagination in Rails views. ```ruby AlgoliaSearch.configuration = { pagination_backend: :kaminari } # Kaminari results = Product.search('laptop', page: 2) <%= paginate results %> # Pagy pagy, results = Product.search('laptop', page: 1, hitsPerPage: 20) <%== pagy_nav(pagy) %> ``` -------------------------------- ### Perform Backend Search in Rails Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Executes a search query against the Algolia index using the provided search term. It returns ORM-compliant objects that are reloaded from the database. The raw JSON answer from the API can also be retrieved. ```ruby hits = Contact.search("jon doe") p hits p hits.raw_answer # to get the original JSON raw answer ``` ```ruby json_answer = Contact.raw_search("jon doe") p json_answer p json_answer['hits'] p json_answer['facets'] ``` -------------------------------- ### Configure Index Relevancy and Ranking Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Tunes search results by defining searchable attributes and custom ranking criteria. This allows for precise control over how records are matched and sorted. ```ruby class Product < ActiveRecord::Base include AlgoliaSearch algoliasearch do attributes :title, :subtitle, :description, :likes_count, :seller_name searchableAttributes ['title', 'subtitle', 'unordered(description)'] customRanking ['desc(likes_count)'] end end ``` -------------------------------- ### Configure Searchable Attributes and Relevancy Source: https://context7.com/algolia/algoliasearch-rails/llms.txt Sets up searchable attributes, custom ranking for relevancy, typo tolerance, and results per page for Algolia search within a Rails model. ```ruby class Article < ActiveRecord::Base include AlgoliaSearch algoliasearch do attributes :title, :content, :author, :views_count, :published_at # Define searchable attributes in order of importance searchableAttributes ['title', 'unordered(content)', 'author'] # Custom ranking based on popularity customRanking ['desc(views_count)', 'desc(published_at)'] # Typo tolerance settings minWordSizefor1Typo 4 minWordSizefor2Typos 8 # Results per page hitsPerPage 20 end end # Search with highlighting results = Article.search('rails tutorial', attributesToHighlight: ['title', 'content'], attributesToSnippet: ['content:50'] ) results.each do |article| puts article.highlight_result['title']['value'] # Rails Tutorial puts article.snippet_result['content']['value'] # ...building Rails apps... end ``` -------------------------------- ### Define Custom Attributes for Algolia Indexing in Ruby Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Allows defining complex or computed attributes for Algolia indexing using blocks. It also explains how to handle attribute change detection for custom attributes by defining a `_changed?` method. ```ruby class Contact < ActiveRecord::Base include AlgoliaSearch algoliasearch do attribute :email attribute :full_name do "#{first_name} #{last_name}" end add_attribute :full_name2 end def full_name2 "#{first_name} #{last_name}" end end ``` ```ruby class Contact < ActiveRecord::Base include AlgoliaSearch algoliasearch do attribute :email attribute :full_name do "#{first_name} #{last_name}" end end def full_name_changed? first_name_changed? || last_name_changed? end end ``` -------------------------------- ### Control Indexing with Conditions Source: https://context7.com/algolia/algoliasearch-rails/llms.txt Use the :if and :unless options to selectively index records based on model state. This ensures only relevant data is pushed to the Algolia index. ```ruby class Post < ActiveRecord::Base include AlgoliaSearch algoliasearch if: :published?, unless: :deleted? do attributes :title, :content end def published? published_at.present? && published_at <= Time.current end def deleted? deleted_at.present__at.present? end end Post.where('created_at > ?', 1.week.ago).reindex! ``` -------------------------------- ### Customize Index Name Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Shows how to override the default index name derived from the class name by using the index_name option. ```ruby class Contact < ActiveRecord::Base include AlgoliaSearch algoliasearch index_name: "MyCustomName" do attribute :first_name, :last_name, :email end end ``` -------------------------------- ### Define replica indices in AlgoliaSearch-Rails Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Configures replica indices for an ActiveRecord model using the add_replica method. Supports inheritance of settings from the primary index and environment-specific configurations. ```ruby class Book < ActiveRecord::Base attr_protected include AlgoliaSearch algoliasearch per_environment: true do searchableAttributes [:name, :author, :editor] add_replica 'Book_by_author', per_environment: true do searchableAttributes [:author] end add_replica 'Book_custom_order', inherit: true, per_environment: true do customRanking ['asc(rank)'] end end end ``` -------------------------------- ### Basic Model Integration for Algolia Search Source: https://context7.com/algolia/algoliasearch-rails/llms.txt Integrates AlgoliaSearch into an ActiveRecord model, defining searchable attributes and demonstrating auto-indexing and basic searching. ```ruby class Contact < ActiveRecord::Base include AlgoliaSearch algoliasearch do attributes :first_name, :last_name, :email end end # Auto-indexing happens on save contact = Contact.create!(first_name: 'John', last_name: 'Doe', email: 'john@example.com') # Search returns ORM objects results = Contact.search('john doe') results.each { |contact| puts contact.email } # => john@example.com ``` -------------------------------- ### Implement Custom Reindexing Logic with `algolia_dirty?` in Rails Source: https://github.com/algolia/algoliasearch-rails/blob/master/CHANGELOG.MD Shows how to use the `algolia_dirty?` method on a Rails model to control when a model should be reindexed by Algolia. This provides a centralized way to manage reindexing logic, especially for dynamic attributes not directly mapped to database columns, avoiding the need for multiple `_changed?` method calls. ```ruby class YourModel < ActiveRecord::Base include AlgoliaSearch algoliasearch do # ... your settings ... end def algolia_dirty? # Custom logic to determine if the model needs reindexing # For example, checking specific attributes or associated data attribute_changed?(:your_attribute) || some_other_condition end end ``` -------------------------------- ### Implement Multiple Indices Source: https://context7.com/algolia/algoliasearch-rails/llms.txt Index a single model into multiple Algolia indices with distinct configurations or filtering conditions using add_index. ```ruby class Book < ActiveRecord::Base include AlgoliaSearch algoliasearch index_name: 'all_books' do attributes :name, :author, :premium, :released searchableAttributes ['name', 'author'] add_index 'public_books', per_environment: true, if: :public? do attributes :name, :author searchableAttributes ['name'] end add_index 'books_by_author', per_environment: true do attributes :name, :author searchableAttributes ['author'] end end end ``` -------------------------------- ### Configure Algolia Index Settings Source: https://context7.com/algolia/algoliasearch-rails/llms.txt Customize index behavior including environment-specific naming, auto-indexing, and data sanitization. Demonstrates how to define custom object IDs for Algolia records. ```ruby class User < ActiveRecord::Base include AlgoliaSearch algoliasearch index_name: 'users_directory', per_environment: true, auto_index: true, auto_remove: true, synchronous: false, disable_indexing: Rails.env.test?, id: :custom_object_id, sanitize: true, force_utf8_encoding: true do attributes :name, :email, :role end def custom_object_id "user_#{id}" end end ``` -------------------------------- ### Configure Per-Environment Indices in Ruby Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Suffixes the Algolia index name with the current Rails environment. This is useful for separating development, staging, and production data. It requires the `algoliasearch` method within an ActiveRecord model. ```ruby class Contact < ActiveRecord::Base include AlgoliaSearch algoliasearch per_environment: true do # index name will be "Contact_#{Rails.env}" attribute :first_name, :last_name, :email end end ``` -------------------------------- ### Propagate Nested Child Changes to Algolia Index (Sequel, Ruby) Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Details how to propagate changes from nested child records to the parent's Algolia index using Sequel's `touch` plugin. It includes custom `touch` method implementation to trigger updates on associated records. ```ruby # app/models/app.rb class App < Sequel::Model include AlgoliaSearch many_to_one :author, class: :User plugin :timestamps plugin :touch algoliasearch do attribute :title attribute :author do author.to_hash end end end # app/models/user.rb class User < Sequel::Model one_to_many :apps, key: :author_id plugin :timestamps # Can't use the associations since it won't trigger the after_save plugin :touch # Define the associations that need to be touched here # Less performant, but allows for the after_save hook to trigger def touch_associations apps.map(&:touch) end def touch super touch_associations end end ``` -------------------------------- ### Perform Raw Searches and Direct API Access Source: https://context7.com/algolia/algoliasearch-rails/llms.txt Access raw JSON responses from search queries and interact directly with the Algolia client for advanced configuration and index management. ```ruby json = Product.raw_search('laptop') results = Product.search('laptop', facets: '*') results.raw_answer client = AlgoliaSearch.client client.search_single_index('products', { query: 'laptop' }) client.get_settings('products') ``` -------------------------------- ### Add Dynamic Tags to Records in Rails Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Dynamically generates tags for a record based on its attributes or other conditions when indexing with Algolia. This allows for more flexible filtering and categorization. ```ruby class Contact < ActiveRecord::Base include AlgoliaSearch algoliasearch do tags do [first_name.blank? || last_name.blank? ? 'partial' : 'full', has_valid_email? ? 'valid_email' : 'invalid_email'] end end end ``` -------------------------------- ### Perform Bulk Operations with without_auto_index Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Provides a pattern to temporarily disable auto-indexing during bulk data operations to improve performance, followed by a manual reindex. ```ruby Contact.delete_all Contact.without_auto_index do 1.upto(10000) { Contact.create! attributes } end Contact.reindex! ``` -------------------------------- ### Configure Attributes for Faceting in Rails Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Specifies which attributes should be available for faceting in Algolia search results. This is configured within the `algoliasearch` block in the Rails model. ```ruby class Contact < ActiveRecord::Base include AlgoliaSearch algoliasearch do # [...] # specify the list of attributes available for faceting attributesForFaceting [:company, :zip_code] end end ``` -------------------------------- ### Embed Nested Objects and Relations in Algolia Index (Ruby) Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Demonstrates how to embed nested objects or data from related records into the Algolia index. It shows how to restrict the fields included from associated objects and how to filter and map collections. ```ruby class Profile < ActiveRecord::Base include AlgoliaSearch belongs_to :user has_many :specializations algoliasearch do attribute :user do # restrict the nested "user" object to its `name` + `email` { name: user.name, email: user.email } end attribute :public_specializations do # build an array of public specialization (include only `title` and `another_attr`) specializations.select { |s| s.public? }.map do |s| { title: s.title, another_attr: s.another_attr } end end end end ``` -------------------------------- ### Manual Index Management Operations Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Methods for manually indexing, removing, clearing, and accessing the underlying Algolia index object. ```ruby c = Contact.create!(params[:contact]) c.index! c.remove_from_index! c.destroy Contact.reindex Contact.reindex! Contact.clear_index! index = Contact.index ``` -------------------------------- ### Implement Geo-Search with Algolia Source: https://context7.com/algolia/algoliasearch-rails/llms.txt Configure geolocation attributes for records to enable proximity-based searches. Supports simple attribute mapping or complex block-based logic for multi-location data. ```ruby class Restaurant < ActiveRecord::Base include AlgoliaSearch algoliasearch do attributes :name, :cuisine, :rating geoloc :latitude, :longitude geoloc do if locations.any? locations.map { |l| { lat: l.lat, lng: l.lng } } else { lat: latitude, lng: longitude } end end end end nearby = Restaurant.search('pizza', aroundLatLng: '37.7749, -122.4194', aroundRadius: 5000 ) in_area = Restaurant.search('sushi', insideBoundingBox: [[37.8, -122.5, 37.7, -122.4]] ) ``` -------------------------------- ### Utilize Tags for Simple Search Filtering Source: https://context7.com/algolia/algoliasearch-rails/llms.txt Adds static or dynamic tags to records for straightforward filtering of search results, complementing faceted search. ```ruby class Book < ActiveRecord::Base include AlgoliaSearch algoliasearch do attributes :title, :author # Static tags tags ['books', 'literature'] # Dynamic tags based on record data tags do [ premium ? 'premium' : 'standard', released ? 'public' : 'private', "author_#{author.parameterize}" ] end end end # Filter by tags premium_books = Book.search('fiction', tagFilters: 'premium') public_books = Book.search('', tagFilters: ['public', 'standard']) ``` -------------------------------- ### Disable Indexing in Test Environments Source: https://context7.com/algolia/algoliasearch-rails/llms.txt Demonstrates how to prevent API calls during testing by conditionally disabling indexing using environment checks or Proc objects. ```ruby class Product < ActiveRecord::Base include AlgoliaSearch algoliasearch per_environment: true, disable_indexing: Rails.env.test? do attributes :name end end class Article < ActiveRecord::Base include AlgoliaSearch algoliasearch disable_indexing: Proc.new { Rails.env.test? || ENV['DISABLE_SEARCH'] } do attributes :title end end ``` -------------------------------- ### Disable indexing for testing Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Shows how to conditionally disable Algolia indexing operations using the disable_indexing option, useful for test environments. ```ruby class User < ActiveRecord::Base include AlgoliaSearch algoliasearch per_environment: true, disable_indexing: Rails.env.test? do; end end class User < ActiveRecord::Base include AlgoliaSearch algoliasearch per_environment: true, disable_indexing: Proc.new { Rails.env.test? } do; end end ``` -------------------------------- ### Add Static Tags to Records in Rails Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Assigns a static tag to a record when indexing it with Algolia. This is done within the `algoliasearch` block in the Rails model. ```ruby class Contact < ActiveRecord::Base include AlgoliaSearch algoliasearch do tags ['trusted'] end end ``` -------------------------------- ### Perform Manual Indexing Operations Source: https://context7.com/algolia/algoliasearch-rails/llms.txt Trigger manual indexing for records outside of the standard lifecycle hooks. Supports both asynchronous and synchronous indexing modes. ```ruby product = Product.find(1) product.index! # Async product.index!(true) # Synchronous ``` -------------------------------- ### Configure Algolia Search Settings in Rails Model Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Defines static Algolia search parameters within a Rails model using the `algoliasearch` block. These settings, such as `minWordSizefor1Typo` and `hitsPerPage`, are stored in the index settings. ```ruby class Contact < ActiveRecord::Base include AlgoliaSearch algoliasearch do attribute :first_name, :last_name, :email # default search parameters stored in the index settings minWordSizefor1Typo 4 minWordSizefor2Typos 8 hitsPerPage 42 end end ``` -------------------------------- ### Search for Facet Values in Rails Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Enables searching for specific facet values within a given attribute. This method can also accept query parameters to refine the search for facet values. ```ruby Product.search_for_facet_values('category', 'Headphones') # Array of {value, highlighted, count} ``` ```ruby # Only sends back the categories containing red Apple products (and only counts those) Product.search_for_facet_values('category', 'phone', { query: 'red', filters: 'brand:Apple' }) # Array of phone categories linked to red Apple products ``` -------------------------------- ### Share a single index across multiple models Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Allows multiple models to share the same Algolia index. Requires a custom unique objectID generation to prevent record conflicts. ```ruby class Student < ActiveRecord::Base include AlgoliaSearch algoliasearch index_name: 'people', id: :algolia_id do; end private def algolia_id; "student_#{id}"; end end class Teacher < ActiveRecord::Base include AlgoliaSearch algoliasearch index_name: 'people', id: :algolia_id do; end private def algolia_id; "teacher_#{id}"; end end ``` -------------------------------- ### Retrieve and Access Facets in Rails Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Shows how to retrieve facet information from Algolia search results in Rails. The `facets` method is added to the search results, allowing access to facet counts for specified attributes. ```ruby hits = Contact.search('jon doe', { facets: '*' }) p hits # ORM-compliant array of objects p hits.facets # extra method added to retrieve facets p hits.facets['company'] # facet values+count of facet 'company' p hits.facets['zip_code'] # facet values+count of facet 'zip_code' ``` ```ruby raw_json = Contact.raw_search('jon doe', { facets: '*' }) p raw_json['facets'] ``` -------------------------------- ### Propagate Nested Child Changes to Algolia Index (ActiveRecord, Ruby) Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Explains how to ensure changes in nested child records propagate to the parent record's Algolia index using ActiveRecord's `touch` and `after_touch` callbacks. This keeps the Algolia index synchronized. ```ruby # app/models/app.rb class App < ApplicationRecord include AlgoliaSearch belongs_to :author, class_name: :User after_touch :index! algoliasearch do attribute :title attribute :author do author.as_json end end end # app/models/user.rb class User < ApplicationRecord # If your association uses belongs_to # - use `touch: true` # - do not define an `after_save` hook has_many :apps, foreign_key: :author_id after_save { apps.each(&:touch) } ``` -------------------------------- ### Configure Custom `objectID` for Algolia Indexing in Ruby Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Explains how to override the default `objectID` generation (which uses the record's `id`) by specifying a unique field using the `:id` option in the `algoliasearch` configuration. This ensures unique identification in Algolia. ```ruby class UniqUser < ActiveRecord::Base include AlgoliaSearch algoliasearch id: :uniq_name do end end ``` -------------------------------- ### Configure Attribute for Distinct (Grouping) in Rails Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Sets the attribute to be used for distinguishing records, enabling grouping of search results by a specific field. This is configured within the `algoliasearch` block in the Rails model. ```ruby class Contact < ActiveRecord::Base include AlgoliaSearch algoliasearch do # [...] # specify the attribute to be used for distinguishing the records # in this case the records will be grouped by company attributeForDistinct "company" end end ``` -------------------------------- ### Define Algolia Index Schema in Models Source: https://github.com/algolia/algoliasearch-rails/blob/master/README.md Configures how ActiveRecord models are indexed in Algolia. It supports selecting specific attributes, including all attributes, or adding custom computed attributes. ```ruby class Contact < ActiveRecord::Base include AlgoliaSearch algoliasearch do attributes :first_name, :last_name, :email end end class Product < ActiveRecord::Base include AlgoliaSearch algoliasearch do add_attribute :extra_attr end def extra_attr "extra_val" end end ``` -------------------------------- ### Manage Algolia Index Operations Source: https://context7.com/algolia/algoliasearch-rails/llms.txt Methods for removing, reindexing, and clearing records from an Algolia index. Supports both synchronous and asynchronous execution modes. ```ruby product.remove_from_index! product.remove_from_index!(true) Product.reindex Product.reindex! Product.reindex!(500) Product.where(category: 'Electronics').reindex! Product.index_objects(Product.where(featured: true)) Product.clear_index! Product.clear_index!(true) ``` -------------------------------- ### Custom Attributes and Computed Fields for Indexing Source: https://context7.com/algolia/algoliasearch-rails/llms.txt Defines custom and computed attributes within the `algoliasearch` block to transform or enrich data before it's indexed by Algolia. ```ruby class Product < ActiveRecord::Base include AlgoliaSearch algoliasearch do attribute :name, :price # Computed attribute with block attribute :full_title do "#{brand} - #{name}" end # Add extra attributes to default model attributes add_attribute :discount_price do price * 0.9 end end # Optional: optimize change detection def full_title_changed? brand_changed? || name_changed? end end ``` -------------------------------- ### Disable Automatic Algolia Settings Check in Rails Source: https://github.com/algolia/algoliasearch-rails/blob/master/CHANGELOG.MD Demonstrates how to disable the automatic checking and pushing of Algolia settings for a Rails model. This is useful to reduce API calls if your settings are static or managed separately. It involves adding `check_settings: false` to the `algoliasearch` configuration block. ```ruby class Musician < ActiveRecord::Base include AlgoliaSearch algoliasearch check_settings: false do # Settings... end end ``` -------------------------------- ### Disable Auto-Indexing for Bulk Operations Source: https://context7.com/algolia/algoliasearch-rails/llms.txt Temporarily suspends auto-indexing during bulk database updates to optimize performance. Requires manual reindexing after the block completes. ```ruby Product.without_auto_index do 1000.times { |i| Product.create!(name: "Product #{i}", price: rand(100)) } Product.where('price < 10').update_all(price: 10) end Product.reindex! ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.