[英]Rails: Convert a complex SQL query to Arel or ActiveRecord
[英]Assemble a complex SQL query using Activerecord::Relation and/or Arel with 'joins', 'as', and 'like'
我正在使用datatables( http://datatables.net )構建Rails 3.2應用程序,其中大多數html表具有客戶端分頁和過濾功能,而其他html表具有服務器端分頁和過濾功能。 我想執行每列過濾,這對於客戶端表來說非常容易,但是我想我需要為數據庫構造一個sql查詢,以便對服務器端表進行每列過濾。 我密切關注了RailsCast#340中有關數據表的示例,並使其正常運行。
面臨的挑戰是對實際上與另一張表的foreign_key關系的列進行排序和過濾。 我不想對foreign_key值的實際內容進行排序和過濾。 我想對鏈接對象顯示的'.to_s'值進行排序和過濾(這是使用客戶端排序和過濾功能的語義)。 這是一個例子:
class Address < ActiveRecord::Base
attr_accessible :city, :line1, :line2, :state, :zip
has_many :people
def to_s
[line1, line2, city, state, zip].join(' ')
end
end
class Person < ActiveRecord::Base
attr_accessible :address, :name
belongs_to :address
end
因此顯示人員列表的視圖有兩列,分別是姓名和地址
<td><%= p.name %></td>
<td><%= p.address %></td>
索引表中顯示的是
John Smith | 1234 Main St Anywhere City AA 12345
因此,利用客戶端的排序和過濾功能,我可以在地址欄中搜索“任意位置”,並在地址字段中獲取包含該詞條的所有行。 在服務器端做同樣的事情似乎要困難得多。 我想我正在嘗試組裝一個看起來像這樣的sql查詢:
select * from people
join address on people.address_id = address.id
where concat(address.line1,
address.line2,
address.city,
address.state,
address.zip) as spec_address like query_term
order by spec_address
(這不一定是正確的SQL代碼。)
我已經看過ActiveRecord Query Rails指南以及在Arel上找不到的任何內容。
您可以使用Address
上的作用域執行此操作,然后將其合並到Person
查詢中。
class Address < ActiveRecord::Base
scope :anywhere, lambda{|search|
attrs = [:line1, :line2, :city, :state, :zip]
where(attrs.map{|attr| "addresses.#{attr} LIKE :search"}.join(' OR '), search: "#{search}%").
order(*attrs)
}
end
Person.joins(:address).merge(Address.anywhere(query_term))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.