2016-11-24 81 views
0

我試圖選擇兩個字段沒有相同值的記錄。 (其中字段A與字段B不具有相同的值)。這涉及到alias_attributes。我希望能夠使用別名而不是隱含的數據庫名稱,以便可以將rails代碼與數據庫名稱隔離。ActiveRecord通過字段比較來選擇

型號:

alias_attribute :item_amount, :fielda 
alias_attribute :item_applied_amount, :fieldb 

此代碼的工作:

query = where('fielda != fieldb') 

但我寧願有類似:

query = where.not(item_amount: item_applied_amount:) 

回答

3

恕我直言,你不能這樣做,因爲數據庫知道沒有關於您的模型中定義的別名。

此外,即使別名正在工作,where(item_amount: :item_applied_amount)也會轉換爲SQL中的fielda = 'fieldb'。這是指:fielda列的值必須等於字符串"fieldb"(而不是列fieldb的值)

但是你可以用attribute_alias(name)來獲得原始名稱,並使用返回的字符串建立一個適當的查詢:

where(
    "#{attribute_alias(:item_amount)} != #{attribute_alias(:item_applied_amount)}" 
) 

或者,您可能希望定義一個範圍,提高可讀性 - :

scope :without_matching_amounts, -> { where('fielda != fieldb') } 

,並使用它像這樣:

query = Model.without_matching_amounts 
+0

這當然更是我正在尋找,並與它的作品稍加修改其意義可以理解。 where(「#{attribute_alias(:item_amount)}!=#{attribute_alias(:item_applied_amount)}」) –

0

像@spickermann說的,alias做了一個ruby方法的別名,並沒有在SQL中創建別名。

你可以做的是創建這樣的別名:

scope :with_aliases, -> { 
    select('table.*, table.item_amount as fielda, table.item_applied_amount as fieldb') 
} 

然後像做:

Model.with_aliases.where('fielda <> fieldb') 
+0

對不起,如果我沒有足夠清楚。我試圖不使用神祕的名字「fielda」和「fieldb」,因爲它們在字段名稱代表的內容中不清楚。 「fielda」不會告訴某人它代表「item_value」,因此乍一看很難理解。 –