【问题标题】:How to write searchable method for belongs_to assocication using sunspot_rails gem如何使用 sunspot_rails gem 为 belongs_to 关联编写可搜索的方法
【发布时间】:2012-04-05 03:14:06
【问题描述】:

我有两个模型。一个是品牌,另一个是product_detail。 Brands 表有 id 和 name 字段,product_details 表有 id、name、price、discount 和 brand_id 字段。

brand有很多product_details,product_detail属于brand

brand.rb 看起来像:

class Brand < ActiveRecord::Base
    has_many :product_details
end

product_details.rb 看起来像

class ProductDetail < ActiveRecord::Base
    belongs_to :Brand, :dependent=>:destroy
end

我正在尝试使用太阳黑子轨道进行搜索。我想使用用户输入的文本根据品牌名称和产品名称进行搜索。为此,我编写了这样的可搜索方法:

class ProductDetail < ActiveRecord::Base
    belongs_to :brands, :dependent=>:destroy

     searchable do
      text :name
      text :brands do
        brands.map(&:name)
      end
    end
end

当我运行 rake sunspot:reindex

它为 nil 类抛出一个错误未定义的方法映射

如果像这样更改代码

class ProductDetail < ActiveRecord::Base
    belongs_to :Brand, :dependent=>:destroy

     searchable do
      text :name
      text :Brand do
        brands.map(&:name)
      end
    end
end

它为 product_detail 类抛出一个错误 undefined methodbrands

请帮助我如何做到这一点。

【问题讨论】:

    标签: ruby-on-rails-3 full-text-search sunspot sunspot-rails sunspot-solr


    【解决方案1】:

    应该是

    belongs_to :brand, :dependent=>:destroy
    

    但是您确定要在删除与之关联的 product_detail 时删除该品牌吗?

    在任何情况下,可搜索块都应该写成

    searchable do
      text :name
      text :brand do
        brand.name
      end
    end
    

    我希望,这会有所帮助。

    【讨论】:

    • 不,我不想在删除产品时删除品牌。这是我的错误,我在 product_details 模型而不是品牌模型中依赖=>destroy。我会改正我的错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-21
    • 2016-07-07
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 2015-11-06
    相关资源
    最近更新 更多