1

我有一个记录电话的应用程序。每个调用可以有多个与之关联的单元。我的应用程序的一部分有一个报告部分,它基本上只是针对不同标准对 Call 模型进行查询。我已经想出了如何编写一些可以做我想做的事情并将它们链接到我的报告搜索功能的结果。但我不知道如何按“单位”搜索。以下是我的代码的相关摘录:

Call.rb

    has_many :call_units
    has_many :units, through: :call_units

        #Report search logic
          def self.report(search)
            search ||= { type: "all" }

            # Determine which scope to search by
            results = case search[:type]
                      when "open"
                        open_status
                      when "canceled"
                        cancel
                      when "closed"
                        closed
                      when "waitreturn"
                        waitreturn
                      when "wheelchair"
                        wheelchair
                      else
                        scoped
                      end

#Search results by unit name, this is what I need help with.  Scope or express otherwise?          
results = results. ??????

            results = results.by_service_level(search[:service_level]) if search[:service_level].present?
            results = results.from_facility(search[:transferred_from]) if search[:transferred_from].present?
            results = results.to_facility(search[:transferred_to]) if search[:transferred_to].present?

            # If searching with BOTH a start and end date
            if search[:start_date].present? && search[:end_date].present?
              results = results.search_between(Date.parse(search[:start_date]), Date.parse(search[:end_date]))

              # If search with any other date parameters (including none)
            else
              results = results.search_by_start_date(Date.parse(search[:start_date])) if search[:start_date].present?
              results = results.search_by_end_date(Date.parse(search[:end_date])) if search[:end_date].present?
            end

            results
          end

由于我已经与单位建立了关联,因此我不确定是否需要以某种方式为单位设定范围,或者以某种方式在搜索逻辑的结果变量中表达结果。

4

1 回答 1

1

基本上,您想要一个使用连接的范围,以便您可以where针对关联模型使用标准?那是对的吗?

所以在 SQL 中你正在寻找类似的东西

select * from results r 
    inner join call_units c on c.result_id = r.id 
    inner join units u on u.call_unit_id = c.id 
    where u.name = ?

并且范围将是(从内存中,我没有调试过这个)类似于:

scope :by_unit_name, lambda {|unit_name|
  joins(:units).where('units.unit_name = ?', unit_name)
}

units.name 不是数据库中的列。将其更改为 units.unit_name 并没有引发异常,这似乎是我想要的。这是我的结果变量中的内容:

results = results.by_unit_name(search[:unit_name]) if search[:unit_name].present?

当我尝试按不同的单位名称搜索时,没有显示结果。这是我用来搜索的代码:

<%= select_tag "search[unit_name]", options_from_collection_for_select(Unit.order(:unit_name), :unit_name, :unit_name, selected: params[:search].try(:[], :unit_name)), prompt: "Any Unit" %>
于 2013-10-17T19:08:56.653 回答