繁体   English   中英

使用Ransacker筛选关系

[英]Using Ransacker to filter through relations

我的Rails应用程序中有以下模型实体:

class Artist < ActiveRecord::Base
  has_many :albums
end

class Album < ActiveRecord::Base
  belongs_to :artist
  has_many :tracks
end

class Track < ActiveRecord::Base
  belongs_to :album
end

我正在尝试在“专辑”实体的索引视图中实现搜索表单,我需要选择所有artist.name以我的搜索参数开头的专辑。 我在处理直接模型搜索方面取得了成功,但是这种情况下,必须验证父属性以选择子元素,这令人有些头痛。

我已经阅读了Ransacker文档,但没有找到与此相关的任何东西:(

为了以一般方式解决此问题,我创建了一个文件_search.html.slim,其中包含“常规搜索逻辑”,从而允许进行“简单”搜索(不具有关联)和复杂搜索(具有关联):

= search_form_for @search, url: request.original_url do |f|
  = f.condition_fields do |c|
    .field
      = c.attribute_fields do |a|
        - if local_assigns.has_key? :associations
          = a.attribute_select associations: associations
        - else
          = a.attribute_select
      = c.predicate_select compounds: false, only: [:cont, :not_cont, :eq, :lteq, :gteq, :lt, :gt]
      = c.value_fields do |v|
        = v.text_field :value
  .form-actions
    = f.submit 'Search', class: 'btn btn-primary'

我在索引文件中使用的

= render 'search', associations: [:artist]

通过我想搜索的关联,或者

= render 'search'

如果没有关联

我的控制器看起来像

def index
  @search = @albums.includes(:artist).search(params[:q])
  @albums = @search.result(distinct: true).paginate(per_page: 10, page: params[:page])
  @search.build_condition
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM