Rubytastic
Rubytastic

Reputation: 15491

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

Upvotes: 4

Views: 3112

Answers (1)

carols10cents
carols10cents

Reputation: 7014

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

Upvotes: 2

Related Questions