I have a Topic that has_many comments. In the search results only want
Topics to show up, but I want them to include the text of the comments
that they have when they are indexed. To do this I've added a
:comments_text field for acts_as_ferret and the comments_text method
gathers the text from all comments up into a string that can be indexed.

The trick is that when comments are added, updated, or deleted the Topic
needs to be updated in the ferret index, and I'm not sure what the best
way to enforce that is. I've included my current code to do this, which
seems to work, but I'd like to know if there is a better way to maintain
this dependency then what I'm doing. In particular am I using
appropriate callback methods in Comment to trigger the updates on Topic
(ie. after_create, after_update, after_destroy). And to make the destroy
case work I'm needing to call unless each.frozen? in the comments_text
method... is that the right thing to do?

Thanks. Here's my existing code:

class Topic < ActiveRecord::Base
  acts_as_ferret :store_class_name => true, :fields => {
      :comments_text => { :store => :yes } }

  has_many :comments, :as => :commentable, :dependent => :destroy

  def comments_text
    result = ""
    for each in comments
      unless each.frozen?
        result << " "
        result << each.subject
        result << " "
        result << each.body
      end
    end
    result
  end
end

class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true

  def after_create
    commentable.ferret_update
  end

  def after_update
    commentable.ferret_update
  end

  def after_destroy
    commentable.ferret_update
  end
end

-- 
Posted via http://www.ruby-forum.com/.
_______________________________________________
Ferret-talk mailing list
[email protected]
http://rubyforge.org/mailman/listinfo/ferret-talk

Reply via email to