如何从模型内部检查ActiveRecord中是否存在关联?

时间:2013-10-19 15:36:13

标签: ruby-on-rails associations ruby-on-rails-4 rails-activerecord sunspot-solr

我尝试了所有可以在网上找到的组合,它总是失败。

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

Match belongs_to :profile

我在Profile模型中尝试:

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

  end

1 个答案:

答案 0 :(得分:2)

the blog post that Olivier linked toconfirmed in the Sunspot documentation的启发,你可以这样做:

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