2

摘要: 基本上,我希望用戶輸入分隔符的標題來篩選分佈列表。一個發行版有一個配置文件,但一個合作伙伴有很多發行版。所以,如果有人將一個合作伙伴標題放入搜索表單中。這將對應於多個分配ID(通過多個matching_profile ID)。通過多個模型篩選故障

我應該描述問題的三種型號:

distribution: 
    belongs_to :matching_profile, :counter_cache => true 

matching_profile: 
    belongs_to :partner 

partner: 
    has_many :matching_profiles 

我基本上需要通過分銷模式訪問partner.title。這裏 ,有效的,是我想要做什麼:

我能做到這一點的SQL: select d.* from distributions d join matching_profiles m on d.matching_profile_id = m.id join partners p on m.partner_id = p.id where p.title in ('TITLE') /總結

更新。雖然有一些缺口......請幫忙!

在我的控制器

我有:

@search = Distribution.workflow.order(sort_column + " " + sort_direction).search(params[:traits_searchable_search]) 
視圖

我:

<%= form_for @search, :url => url_for(:controller => params[:controller], :action => params[:action]), :html => {id => "distribution_workflow",:method => :get} do |f| %> 

<div class="form-block mrl mbm mtm"> 
     <%= f.label 'matching_profile.partner.title_equal', "Partner" %> 
     <%= f.select @search.where('matching_profile_id in (select id from matching_profiles where partner_id in (select id from partners where title in (?)))'), Partner.select(:title), :include_blank => " " %> 
    </div> 

的f.select部分是什麼,是不正確,但我認爲的想法是什麼我想要做的就是在這裏拍攝。我只是不知道如何去做。 /更新

我正在網頁上呈現一個報告,我需要允許用戶根據合作伙伴的標題篩選出哪些行可用。然而,合作伙伴的標題並不在我創建表單的模型中。表單用於分發模型,該模型引用了match_profile,該文檔對partner有參考。合作伙伴表格是包含我想過濾的標題的表格。

目前,我試圖通過添加另一個search_scope

search_scopes :equal => [:status, 'matching_profile.partner.title'] #obviously very wrong 

更新來實現:我也試過這樣:

search_scopes :equal => [:status, 'distributions.matching_profile.partner.title'] 

這不會給我一個錯誤,但不會過濾掉無論是。在正確方向邁出的一步? /更新

但我得到一個錯誤,因爲我似乎無法「跳」兩個表來獲得標題。我看到這個錯誤消息:

AND (matching_profile.partner.title = 'PARTNER_TITLE') 
當然

,這是錯誤的,因爲沒有matching_profile場,只有matching_profile_id。

我不確定最好的方法是什麼。任何建議表示讚賞。

+0

你的模型中是否有任何[':through'](http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html)關係? – sarnold 2011-12-29 05:17:21

+0

否':通過'。只是':belongs_to' – Ramy 2011-12-29 13:44:24

+0

對':through'關鍵字做了一點研究 - 看起來像我需要的東西走向另一個方向,即':belongs_to'上的快捷鍵而不是':has_many' – Ramy 2011-12-29 15:22:48

回答

0

好吧,我最終不得不做的是在我的可搜索特徵中添加一個新選項以允許搜索。從那裏我必須做一些重新調整以使序列化開心,但是一旦我意識到我可以擴展可搜索的特徵,它就相對簡單了。我加了這一點:

unless options[:in].blank? 
     [options[:in]].flatten.each do |field| 
     scope "#{field}_in", lambda {|value| Rails.logger.info('value: ' + value.to_s) 
     vals = [] 
     value.each do |v| 
      vals << v.split(',') unless v.blank? || v.nil? 
     end 
     {:conditions => ["#{table_names(field)}#{field} in (?)", vals.flatten ]}} 
     end 
    end 

然後在我的發行模式,我說:

search_scopes :in => [:matching_profile_id] 

終於在我看來,我可以這樣做:

<div class="form-block mrl mbm mtm"> 
    <%= f.label :matching_profile_id_in, "Partner" %> 
    <%= f.select :matching_profile_id_in, Partner.all.map { |p| [p.title, MatchingProfile.find_all_by_partner_id(p.id).map {|m| m.id}.join(',')]}, {:include_blank => " "}, {:multiple => true} %> 
</div> 

和控制器奇蹟般地保持不變。