【问题标题】:How do I check if an association exists in ActiveRecord from inside a model?如何从模型内部检查 ActiveRecord 中是否存在关联?
【发布时间】:2013-10-28 08:48:21
【问题描述】:

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

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

【问题讨论】:

  • 您不能在班级级别执行unless match.present?,因为您在这里没有使用特殊的 Profile 实例。匹配的不是 Profile 类,而是配置文件实例。
  • @OlivierElMekki 那么如何使用 lambda 呢?
  • 我自己不使用 sunspot,但它似乎可以处理通过 proc as :if option 的条件索引。

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-17
    • 1970-01-01
    • 2012-05-30
    • 1970-01-01
    相关资源
    最近更新 更多