0

第一次尝试与 Sphinx/Thinking Sphinx 相处。

我的模型定义如下(简化):

class Branch < ActiveRecord::Base
  has_many  :salesmen, :class_name => "User"
  has_many :leads, :through => :salesmen
end

class User < ActiveRecord::Base
  belongs_to :branch
  has_many :leads, :foreign_key => "owner_id"
end

class Lead < ActiveRecord::Base
  belongs_to :owner, :class_name => "User"

  define_index do
    indexes company_name    
    indexes :name, :sortable => true
    has owner.branch_id, :as => :branch_id
    indexes [owner.last_name, owner.first_name], :as => :owner_full_name, :sortable => true 
  end

end

任何时候我打电话

Branch.first.leads.search

我明白了

RuntimeError: Missing Attribute for Foreign Key branch_id

我究竟做错了什么?

4

3 回答 3

3

问题是 Thinking Sphinx 需要branch_id作为索引中的一个属性,因此它可以将结果限制为相关分支(因为您正在关联中搜索)。

从您的协会(或者可能只是我对睡眠的迫切需要)中尚不清楚潜在客户是通过所有者还是直接属于分支机构。如果是前者,Ben 的建议可能是正确的。否则,请尝试将以下内容添加到您的define_index块中:

has branch_id, :as => :direct_branch_id

阅读评论后,另一种方法是将您自己的搜索方法添加到 Branch 中的潜在客户关联中。一个模糊的尝试(你需要调试,我敢肯定):

has_many :leads, :through => :salesmen do
  def search(*args)
    options = args.extract_options!
    options[:with] ||= {}
    options[:with][:branch_id] = proxy_owner.id
    args << options
    Lead.search(*args)
  end
end

这应该可以解决您没有直接引用 Lead 分支的事实。唯一可能的问题是我不确定自定义扩展是在 Thinking Sphinx 注入之前还是之后加载的。试一试,看看有没有帮助。

于 2009-04-28T20:25:22.937 回答
0

如果您说 Lead belongs_toa Branch,那么您必须branch_id在潜在客户表中有一个。既然你没有,那就不是belongs_to关系。我认为你需要这样的东西:

class Branch < ActiveRecord::Base
  has_many :leads, :through => :salesmen
  has_many :salesmen, :class_name => "User" 
end

class User < ActiveRecord::Base
  belongs_to :branch # users table has branch_id
  has_many :leads, :foreign_key => "owner_id"
end

class Lead < ActiveRecord::Base
  belongs_to :owner, :class_name => "User" # leads table has owner_id

  define_index do
    indexes :company_name    
    indexes :name, :sortable => true
    has owner.branch_id, :as => :branch_id
    indexes [owner.last_name, owner.first_name], :as => :owner_full_name, :sortable => true 
  end

end
于 2009-04-28T23:58:59.680 回答
0

我相信您在分支关系中缺少 :through 选项。尝试更新为:

class Lead < ActiveRecord::Base
  has_one :branch, :through => :owner
于 2009-04-28T18:48:07.557 回答