【问题标题】:Rails tire(elasticsearch) search through has_many associationRails 轮胎(弹性搜索)通过 has_many 关联搜索
【发布时间】:2015-08-07 17:34:38
【问题描述】:

我有 2 个关联

belongs_to :author
has_many :favorites

我想知道为什么这个例子有效:

tire.search(load: {include: [:author, :comments]}, page: params[:page], per_page: 8) do
  query { string params[:query], default_operator: "AND" } if params[:query].present?
  filter :term, author_id: ['111']
  sort { by :created_at, 'desc' }
end

而这个没有:

tire.search(load: {include: [:author, :comments]}, page: params[:page], per_page: 8) do
  query { string params[:query], default_operator: "AND" } if params[:query].present?
  filter :term, favorite_ids: ['567']
  sort { by :created_at, 'desc' }
end

谁能帮帮我?

【问题讨论】:

    标签: ruby-on-rails elasticsearch tire


    【解决方案1】:

    外键存储在子表中,Rails 会为您连接两个表。

    所以在这个模型中,有一个属性author_id,因为这个模型属于一个作者。收藏关系的外键存储在收藏夹表中。虽然你可以通过Model.first.favorites 得到对应的favorites,但这是因为后一个表中存储了一个值。

    Model.first.author_id 存在。 Model.first.favorite_ids 没有。

    如果您想在 favorites_ids 上运行搜索,则需要在 to_indexed_json 方法中明确定义。

    另外,tire 已停用。您应该考虑迁移到 elasticsearch-rails,或我的首选 gem,searchkick

    【讨论】:

    • 不幸的是,我无法切换到另一个 gem。正如你所说,我已经添加了这个代码def to_indexed_json to_json( include: :favorites ) end,但它并没有给我任何改变。我做错了什么?
    • 我不确定你是否可以只使用include 并声明孩子。您可以尝试像这样添加它们吗? def to_indexed_json favorite_ids: favorites.collect{|f| f.id} end?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-27
    • 2012-08-17
    • 2012-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多