聚合多对多活动记录

时间:2020-01-09 13:38:52

标签: ruby-on-rails elasticsearch searchkick

我想在多对多的ActiveRecord模型上进行ES聚合,但是没有办法 我的模特:

<ng-container *ngFor="let i = index; let column of columnsToDisplay" 
    matColumnDef="{{column}}">
    <th mat-header-cell *matHeaderCellDef> {{column | titlecase}} </th>
    <td mat-cell *matCellDef="let element">
       <span *ngIf="column !== 'action'">{{element[column]}}</span>
        <span *ngIf="column == 'action'">
          <button mat-icon-button (click)="deleteRowData(element)" 
            color="primary">
            <mat-icon>delete</mat-icon>
          </button>
        </span>
    </td> 
</ng-container>

我尝试了很多解决方案,但总是得到

 class Foo <  ApplicationRecord
  searchkick
  def search_data
    {
        bar: bar
    }
  end
  has_many :bars
end

2 个答案:

答案 0 :(得分:0)

答案是添加此内容:

 def search_data
    Attributes.merge(
      bar_names: bar.map(&:name)
    )
  end

答案 1 :(得分:0)

更多有关如何使用关联模型的信息,这里是:

Item.rb(模型):

  # Relations
  belongs_to :brand

    ## many-to-many relations between Items and Textures
    has_many   :item_attribute_for_textures
    has_many   :textures, through: :item_attribute_for_textures, :class_name => 'ItemAttribute::Texture'


    # Searchkick
  searchkick

  def search_data
    {
      full_item_title:  full_item_title,
      brand:            brand.try(:title),
      texture:          textures.map(&:title)
    }
  end   

ItemController.rb:

  def index
    args = {}
    args[:brand]          = params[:brand]          if params[:brand].present?
    args[:texture]        = params[:texture]        if params[:texture].present?

    query = params[:busca].presence || "*"
    @items  = Item.search query, where: args, 
      aggs: { 
          full_item_title:  {},
          brand:            {},
          texture:          {}
          }
  end

并查看index.html.erb:

<div class="row">
  <div class="col-sm-2" style="font-size: 0.75rem">

    <h5>Brands</h5>
    <div>
      <% @items.aggs["brand"]["buckets"].sort_by{ |b| b["key"] }.each do |bucket| %>
        <div>
          <% if params[:brand] == bucket["key"].to_s %>
            <strong><%= bucket["key"] %></strong>
          <% else %>
            <%= link_to bucket["key"], request.params.merge(brand: bucket["key"]) %>
          <% end %>
          (<%= bucket["doc_count"] %>)
        </div>
      <% end %>
    </div>
    <hr>

    <h5>Texture</h5>
    <div>
      <% @items.aggs["texture"]["buckets"].sort_by{ |b| b["key"] }.each do |bucket| %>
        <div>
          <% if params[:texture] == bucket["key"].to_s %>
            <strong><%= bucket["key"] %></strong>
          <% else %>
            <%= link_to bucket["key"], request.params.merge(texture: bucket["key"]) %>
          <% end %>
          (<%= bucket["doc_count"] %>)
        </div>
      <% end %>
    </div>
    <hr>

  </div>
</div>