簡體   English   中英

過濾和全球化

[英]Filterrific and Globalize

似乎 filterrific 沒有考慮翻譯表中的內容( Globalize )。

無論如何也可以搜索翻譯表嗎? 如果內容在實際模型中,我的設置工作得很好。 但是,一旦這些字段為空並且只輸入到翻譯表中,就不會顯示任何結果(顯然)。

我的型號:

class Manual < ApplicationRecord
  translates :title, :content, :teaser, :slug

  extend FriendlyId
  friendly_id :title, :use => :globalize

  belongs_to :user
  belongs_to :support_category
  has_many :manual_faqs
  has_many :faqs, :through => :manual_faqs

  validates :title, presence: true
  validates :content, presence: true
  validates :user_id, presence: true

  update_index('manuals#manual') { self }

  filterrific(
      default_filter_params: { sorted_by: 'created_at_desc' },
      available_filters: [
          :sorted_by,
          :search_query,
          :with_user_id,
          :with_created_at_gte
      ]
  )

  scope :with_user_id, lambda { |user_ids|
    where(user_id: [*user_ids])
  }

  scope :search_query, lambda { |query|
    # Searches the students table on the 'first_name' and 'last_name' columns.
    # Matches using LIKE, automatically appends '%' to each term.
    # LIKE is case INsensitive with MySQL, however it is case
    # sensitive with PostGreSQL. To make it work in both worlds,
    # we downcase everything.
    return nil  if query.blank?

    # condition query, parse into individual keywords
    terms = query.downcase.split(/\s+/)

    # replace "*" with "%" for wildcard searches,
    # append '%', remove duplicate '%'s
    terms = terms.map { |e|
      ('%' + e.gsub('*', '%') + '%').gsub(/%+/, '%')
    }
    # configure number of OR conditions for provision
    # of interpolation arguments. Adjust this if you
    # change the number of OR conditions.
    num_or_conds = 2
    where(
        terms.map { |term|
          "(LOWER(manuals.title) LIKE ? OR LOWER(manuals.content) LIKE ?)"
        }.join(' AND '),
        *terms.map { |e| [e] * num_or_conds }.flatten
    )
  }

  scope :sorted_by, lambda { |sort_option|
    # extract the sort direction from the param value.
    direction = (sort_option =~ /desc$/) ? 'desc' : 'asc'
    case sort_option.to_s
      when /^created_at_/
        # Simple sort on the created_at column.
        # Make sure to include the table name to avoid ambiguous column names.
        # Joining on other tables is quite common in Filterrific, and almost
        # every ActiveRecord table has a 'created_at' column.
        order("manuals.created_at #{ direction }")
      else
        raise(ArgumentError, "Invalid sort option: #{ sort_option.inspect }")
    end
  }

  scope :created_at_gte, lambda { |reference_time|
    where('manuals.created_at >= ?', reference_time)
  }

  def self.options_for_sorted_by
    [
        ['Date received (newest first)', 'created_at_desc'],
        ['Date received (oldest first)', 'created_at_asc']
    ]
  end
end

我的控制器:

  def index
    @filterrific = initialize_filterrific(
        Manual,
        params[:filterrific],
        select_options: {
            sorted_by: Manual.options_for_sorted_by,
            with_user_id: User.options_for_select
        }
    ) or return

    @manuals = @filterrific.find.page(params[:page])

    respond_to do |format|
      format.html
      format.js
    end

  rescue ActiveRecord::RecordNotFound => e
    # There is an issue with the persisted param_set. Reset it.
    puts "Had to reset filterrific params: #{ e.message }"
    redirect_to(reset_filterrific_url(format: :html)) and return
    #respond_with(@references)
  end

我根本不知道 filterrific 但我知道 Globalize,並且由於 filterrific 基於 AR 范圍,因此應該只是加入轉換表以獲得顯示結果的問題。

這是您的search_query范圍修改為加入和搜索加入的翻譯表(為了清楚起見,沒有注釋):

scope :search_query, lambda { |query|
  return nil if query.blank?

  terms = query.downcase.split(/\s+/)

  terms = terms.map { |e|
    ('%' + e.gsub('*', '%') + '%').gsub(/%+/, '%')
  }

  num_or_conds = 2
  where(
    ('(LOWER(manual_translations.title) LIKE ? OR'\
     ' LOWER(manual_translations.content) LIKE ?)' * (terms.count)).join(' AND '),
    *terms.map { |e| [e] * num_or_conds }.flatten
  ).with_translations
}

請注意,我只更改了兩件事:(1)我附加了with_translations ,這是這個 SO 答案中描述的一種方法它加入了當前語言環境的翻譯,以及(2)我已經將manuals表交換為manual_translations表查詢。

因此,如果您在英語語言環境中調用此查詢:

Manual.search_query("foo")

你得到這個 SQL:

SELECT "manuals".* FROM "manuals"
INNER JOIN "manual_translations" ON "manual_translations"."manual_id" = "manuals"."id"
WHERE (LOWER(manual_translations.title) LIKE '%foo%' OR
       LOWER(manual_translations.content) LIKE '%foo%')
      AND "manual_translations"."locale" = 'en'"

請注意, with_translations會自動在manual_translations.locale = 'en'上進行標記,因此您僅過濾掉您的語言環境中的結果,我認為這是您想要的。

讓我知道這是否適合您。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM