Search code examples
ruby-on-railsrubyransack

Using Ransacker to filter through relations


I have the following model entities in my rails application:

class Artist < ActiveRecord::Base
  has_many :albums
end

class Album < ActiveRecord::Base
  belongs_to :artist
  has_many :tracks
end

class Track < ActiveRecord::Base
  belongs_to :album
end

I'm trying to implement a search form within the index view of Album entity which i need to select all albums which artist.name starts with my search parameter. I've got success dealing with direct model searches but this situation, having to verify a parent attribute to select the children elements, it's giving some headaches.

I've read the Ransacker documentation but don't find anything related to that :(


Solution

  • To solve this in a general way, I created a file _search.html.slim, containing the "general search logic", allowing both for "simple" searches (without associations), and complex searches (with associations):

    = search_form_for @search, url: request.original_url do |f|
      = f.condition_fields do |c|
        .field
          = c.attribute_fields do |a|
            - if local_assigns.has_key? :associations
              = a.attribute_select associations: associations
            - else
              = a.attribute_select
          = c.predicate_select compounds: false, only: [:cont, :not_cont, :eq, :lteq, :gteq, :lt, :gt]
          = c.value_fields do |v|
            = v.text_field :value
      .form-actions
        = f.submit 'Search', class: 'btn btn-primary'
    

    which I use in my index files as

    = render 'search', associations: [:artist]
    

    passing the associations I want to search on, or just as

    = render 'search'
    

    in case of no associations

    my controller looks like

    def index
      @search = @albums.includes(:artist).search(params[:q])
      @albums = @search.result(distinct: true).paginate(per_page: 10, page: params[:page])
      @search.build_condition
    end