Rails rake索引任务

时间:2017-12-08 13:33:28

标签: ruby-on-rails ruby ruby-on-rails-4

我正在尝试执行以下索引任务

namespace :search_suggestions do
  desc "Generate search suggestions from items"
  task :index => :environment do
    SearchSuggestion.index_items
  end
end

def self.index_items
  Item.find_each do |item|
    index_term(item.title)
    item.title.split.each { |t| index_term(t) }
  end
end

def self.index_term(term)
  where(term: term.downcase).first_or_initialize.tap do |suggestion|
    suggestion.increment! :popularity
    suggestion.save!
  end
end

但是当我rake search_suggestions:index时,列不会更新为当前值Old并且已删除的数据仍会显示在表格内。

如果我这样做:

def self.index_items
 Search_suggestions.all
  Item.find_each do |item|
    index_term(item.title)
    item.title.split.each { |t| index_term(t) }
  end
end

然后一切都正确更新,但这是正确的方法吗?

更新1

删除项目的流程

 def items_destroy
    @item = Item.find(params[:id])
    @item.destroy
      respond_to do |format|
         format.html { redirect_to store_items_index_path(current_store), notice: 'Item was successfully destroyed.' }
         format.json { head :no_content }
    end
 end

route.rb

match "store/items/destroy"=> "stores#items_destroy", :via => :delete, :as => :store_items_destroy

1 个答案:

答案 0 :(得分:1)

lib/tasks/search_suggestions.rake

namespace :search_suggestions do
  desc "Generate search suggestions from items"
  task :index => :environment do
    IndexItemsService.new.call
  end
end

app/services/index_items_service.rb

class IndexItemsService
  def call
    Item.find_each do |item|
      SearchSuggestion.index_terms([item.title].concat(item.title.split))
    end
    return true
  end
end

app/models/search_suggestion.rb

class SearchSuggestion < ActiveRecord::Base
  // other code
  def self.index_terms(terms)
    terms.each do |term|
      where(term: term.downcase).first_or_initialize.tap do |suggestion|
        suggestion.increment! :popularity
        suggestion.save!
      end
    end
  end
  // other code
end

app/controllers/items_controller.rb

def destroy
  @item = Item.find(params[:id])
  SearchSuggestion.where(term: [item.title].concat(item.title.split)).destroy_all
  @item.destroy
end

危险!这大多会起作用,但它有明显的bug。让我们假设我们有两个标题:'Hello Anton'和'Hello Theopap'。他们都被编入索引。如果我们删除'Hello Anton',它会破坏'Hello Anton'的建议,这是好的,'Anton'也没关系,但它也会破坏'Hello'的建议,这两个建议在我们的2项之间相交。因此,第二项“Hello”的建议也将被删除。我没有看到任何真正的解决方法来解决这个问题,而不改变架构等