0

使用此模型:

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'

我该如何解决?

4

2 回答 2

0

Thinking 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?
于 2012-04-24T02:48:01.740 回答
0

我是这样解决的:

Product.search("something", :select=>"products.*, category.name AS category_name", :joins=>[:category])
于 2012-04-24T07:59:29.587 回答