【问题标题】:Thinking Sphinx Has Many Through Rails思考狮身人面像有许多直通铁轨
【发布时间】:2015-07-28 11:33:10
【问题描述】:

你能帮我想想狮身人面像吗?

关系:

大陆 has_many :国家 has_many :country_reports, 通过: :countries, :class_name => "报告" has_many :publishers, through: :country_reports

预期输出:

我想找到 Continent.first.publishers

请告诉我如何在think sphinx rails中写这个

【问题讨论】:

    标签: thinking-sphinx ruby-on-rails-4.2


    【解决方案1】:

    正如我在 Thinking Sphinx Google 小组中的回答:

    因为您正在搜索发布商,所以您需要修改发布商索引才能使其正常工作。我假设出版商belongs_to :country_report、国家报告belongs_to :country 和国家belongs_to :continent。

    如果您使用 SQL 支持的索引(使用 :with => :active_record 选项),那么您需要在 Publisher 索引中包含以下内容:

    has country_report.country.continent_id, :as => :continent_id
    

    如果你使用实时索引(:with => :real_time),那么它是一样的,但你也必须指定类型:

    has country_report.country.continent_id, :as => :continent_id, :type => :integer
    

    但是,如果在从发布者到大陆的关联链中存在 has_many 或 has_and_belongs_to_many 而不是 belongs_to,那么情况会稍微复杂一些。此外,在这种情况下,发布商可能拥有多个大陆,因此我们在这里处理多个值。

    对于 SQL 支持的索引,稍作更改,更改关联链:

    has country_reports.country.continent_id, :as => :continent_ids
    

    但是对于实时索引,最好在 Publisher 模型上有一个返回必要值或值的方法,然后在索引中使用它:

    # in app/models/publisher.rb
    def continent_ids
      country_reports.collect(&:country).collect(&:continent_id)
    end
    
    # in app/indices/publisher_index.rb
    has continent_ids, :type => :integer, :multi => true
    

    然后,一旦你重建了你的索引,你可以搜索如下(如果合适的话,属性是复数):

    Publisher.search “foo”, :with => {:continent_id => continent.id}
    

    可能也可以工作(尽管多层次的关联可能会混淆):

    continent.publishers.search “foo”
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-17
      • 1970-01-01
      • 2014-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多