Search code examples
ruby-on-railsassociationsruby-on-rails-4rails-activerecordsunspot-solr

How do I check if an association exists in ActiveRecord from inside a model?


I tried all combinations that I could find online and it always fails.

class Profile < ActiveRecord::Base

  belongs_to  :user, :dependent => :destroy
  has_one     :match # educational matches 

  accepts_nested_attributes_for :match
  attr_accessor                 :form

  unless match.present?
    searchable do

      integer :id
      string :country
      string :state
    end
  end
end

and

Match belongs_to :profile

Inside the Profile model I try to do:

  unless profile.match.exist? (does profile have a match association existing?) 
    .. do something

  end

Solution

  • Inspired by the blog post that Olivier linked to and confirmed in the Sunspot documentation, you could do:

    # In your Profile model
    searchable :if => proc { |profile| profile.match.present? } do
      integer :id
      string :country
      string :state
    end