【问题标题】:Filterrific and Globalize过滤和全球化
【发布时间】:2023-03-19 23:11:01
【问题描述】:

似乎 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

【问题讨论】:

    标签: ruby-on-rails globalize filterrific


    【解决方案1】:

    我根本不知道 filterrific,但我知道 Globalize,而且由于 filterrific 是基于 AR 范围的,所以应该只是加入转换表以显示结果。

    这是您的 search_query 范围修改为加入和搜索加入的翻译表(为了清楚起见,没有 cmets):

    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,一个方法described in this SO answer 加入了当前语言环境的翻译,以及(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',因此您只过滤掉您的语言环境中的结果,我认为这就是您想要的。

    让我知道这是否适合你。

    【讨论】:

    • 谢谢克里斯!像魅力一样工作!
    • 太棒了!我注意到where 查询的复杂性超出了必要的程度,因此对其进行了一些简化(见上文)。
    • 抱歉有错误,已修复。现在应该可以工作了,稍微短一些。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多