Thinking-Sphinx在搜索结果中获得连接字段的值

时间:2012-04-21 12:17:18

标签: ruby-on-rails activerecord join model thinking-sphinx

使用这个模型:

class Product < ActiveRecord::Base
    belongs_to :category

    define_index do
        join category

        indexes sku
        indexes category.name, :as => :category_name, :facet => true
    end
end

当我这样做时:

products = Product.search("something")
products[0].category_name if products.size > 0

我收到错误:

NoMethodError: undefined method `category_name'

我该如何解决?

2 个答案:

答案 0 :(得分:0)

思考Sphinx不会为您创建新方法 - 所以您需要自己动手,或者只使用标准的Rails方法来获取名称:

products = Product.search 'something'
products.first.category.name unless products.empty?

# or add the following to your Product model:
def category_name
  category.name
end

# and then....
products = Product.search 'something'
products.first.category_name unless products.empty?

答案 1 :(得分:0)

我这样解决了:

Product.search("something", :select=>"products.*, category.name AS category_name", :joins=>[:category])