2014-07-03 49 views
0

這感覺就像應該已經被回答的東西,但是我的搜索foo讓我失望。Rails 3.2 ActiveRecord從兩個類似的表中選擇結果

用Rails 3.2工作,假設我們有一個對我們在選擇所關心的列足夠同一列,像這樣兩個DB表:

create_table "current_employees" do |t| 
    t.string "first_name" 
    t.string "middle_name" 
    t.string "last_name" 
    . . . more columns 
end 

create_table "ex_employees" do |t| 
    t.string "first_name" 
    t.string "middle_name" 
    t.string "last_name" 
    . . . more columns 
end 

是,製造的例子:剛去它現在。

當人力資源部門想要查找當前或前任員工時,他們不想區分這兩個表格:他們需要可以在任一表格中找到的結果。

如何設置我的模型,控制器,從任一表中獲取結果?

例如,傑克傑克遜在current_employees表中,而傑克奧蘭特在ex_employees表中。當搜索「Jack」時,結果表應該有兩行,一個是傑克傑克遜,另一個是傑克奧蘭特。

更新了來指定Rails 3.2。

+1

此:'CurrentEmployees.joins( 「全外連接ex_employees」),其中(「first_name like'?%'」,「Jack」)'應該可以工作我認爲 – bjhaid

回答

0

你將不得不執行兩個不同的查詢,並得到在單個陣列中所有的結果

search_results = [] 
search_results += CurrentEmployee.where("name like '%Jack%'").all 
search_results += ExEmployee.where("name like '%Jack%'").all 

現在顯示視圖從陣列中的所有記錄

2

如果您不需要更改數據庫,你可以用它做兩個表的聯合視圖,讓你從這個觀點

class Employee < ActiveRecord::Base 
    self.table_name = 'Employeeview' 
    self.primary_key = 'employee_id' 

    protected 

    def readonly? 
    true 
    end 
end 
0

模型不知道你用Rails的版本,你可以ü SE Arel生成外連接的SQL查詢加盟,如:

Arel::Table.new(:current_employees).join(Arel::Table.new(:ex_employees), Arel::Nodes::OuterJoin).on(Arel::Table.new(:current_employees)[:first_name].eq(Arel::Table.new(:ex_employees)[:first_name])) 

其生成的SQL語句查詢:

​​
+1

好點。更新問題以指定我在Rails 3.19上。 –