【问题标题】:thinking-sphinx has_many :through relationships思考狮身人面像 has_many :通过关系
【发布时间】:2011-04-05 02:11:44
【问题描述】:

我在账本和员工之间建立了多对多的关系,我想使用 Thinking-Sphinx (TS) 来搜索 current_staff 成员拥有的账本。

在 Rails 3 控制台中,我尝试了以下操作

> Ledger.search 'test', :include => :staff_ids, :with => {:staff_ids => 1}
Returns []
> Ledger.search 'test', :include => :staff_id,  :condition => {:staff_id => 1}
Returns ledgers which do not belong to staff member with id 1.

账本模型

class Ledger < ActiveRecord::Base
  has_many :employees
  has_many :staff, :through => :employees

  define_index do
    indexes :name
#    indexes staff.id, :as => :staff_id # many to many relationship.
    has staff(:id), :as => :staff_ids # many to many relationship.    

    set_property :delta => true
  end
end

员工模型

class Staff < ActiveRecord::Base
  has_many :employees
  has_many :ledgers, :through => :employees

  define_index do
    indexes username
    indexes surname
    indexes firstname

    set_property :delta => true    # http://freelancing-god.github.com/ts/en/deltas.html    
  end
end

我有以下拐点设置

  inflect.uncountable %w( staff )

我已经尝试过索引,并且在我的 Ledger 模型中,每次更改索引后都会重建和重新启动 TS。

更新1:

我非常接近。 如果我执行 'rake ts:reindex' 然后重新启动我的 Rails 服务器,我在分类帐(与 current_staff 相关联)上的搜索工作正常:

@results = Ledger.search params[:search], :include =>:staff_id, :conditions =>{:staff_id => current_staff.id}

这几乎就像我必须在我的 has_many 上有一个增量:通过模型,这是正确的吗?

更新 2:

我已经开始在thinking-sphinx 文档中使用Delta 和关联。不过好像还是不行。

这是我在 Ledger 模型中添加的内容:

  after_save :set_staff_delta_flag
  ...
  private

  def set_staff_delta_flag
    staff.delta = true
    staff.save
  end

尝试添加新分类帐时出现以下错误:

NoMethodError (undefined method `delta=' for #<Class:0x00000001516340>):
  app/models/ledger.rb:19:in `set_staff_delta_flag'
  app/controllers/ledgers_controller.rb:24:in `create'

【问题讨论】:

    标签: ruby-on-rails thinking-sphinx has-many-through


    【解决方案1】:

    我找到了答案!

    我必须在保存后设置人员增量标志,但由于我有多个我必须为每个人员设置。

    这是我的分类帐模型

    class Ledger < ActiveRecord::Base
      has_many :employees
      has_many :staff, :through => :employees
    
      after_save :set_staff_delta_flag
    
      define_index do
        indexes :name
        indexes staff.id, :as => :staff_id # many to many relationship.
        set_property :delta => true
      end
    
      private
    
      def set_staff_delta_flag
        staff.map{ |s| s.update_attribute("delta", true)}
      end
    end
    

    现在在我的 Rails 应用程序中,如果我为当前员工添加新分类帐并使用以下内容,我可以在搜索结果中看到新分类帐。

    @results = Ledger.search params[:search], :include =>:staff_id, :conditions =>{:staff_id => current_staff.id}
    

    如果有更好的方法,请告诉我。

    【讨论】:

      【解决方案2】:

      当我将 attr_accessor :delta 添加到我正在 delta 索引的模型中时,它自行解决了。

      【讨论】:

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