2012-11-10 38 views
2

3个型号:自定义查询on Rails的3.2

Class Product 
include Mongoid::Document 
has_many :orders, dependent: :destroy, :autosave => true 
#search 
searchable do 
    text :title, :description, :boost => 2.0 
    time :created_at 
end 
end 

Class Order 
include Mongoid::Document 
belongs_to :product 
has_one :dispute, dependent: :destroy, :autosave => true 
end 

Class Dispute 
include Mongoid::Document 
belongs_to :order 
field :buyer_has_requested_refund, :type => Boolean, :default => "false" 
end 

我需要内部products_controller.rbindex行动,获得和排序从高到低与订单中的所有产品都与buyer_has_requested_refund = true

事纠纷如:

def index 
@search = Product.solr_search do |s| 
s.fulltext params[:search] 
s.keywords params[:search] 
s.order_by :disputes_where_buyer_has_requested_refund, :desc 
end 
@products = @search.results 
    respond_to do |format| 
    format.html # index.html.erb 
    end 
end 

谢谢!

+0

在哪个模型中添加了用于索引这些对象的可搜索块。 – Sreehari

+0

在型号'Product.rb'上。我编辑了这个问题,并添加了可搜索的块。非常感谢你! – hyperrjas

回答

0

你应该告诉Solr的索引,你需要排序的搜索信息:

class Product 
include Mongoid::Document 
has_many :orders, dependent: :destroy, :autosave => true 
has_many :disputes, :through => :orders 
#search 
searchable do 
    text :title, :description, :boost => 2.0 
    integer :disputes_where_buyer_has_requested_refund { |product| product.disputes.where(:buyer_has_requested_refund => true).size } 
    time :created_at 
end 
end 

注意相应的重建索引的索引记录值创造了新的纠纷时/销毁。你可以用after_create/after_destroy挂钩进行延迟工作,或者每天重新索引一次,具体取决于你的需求和索引的大小。