有什麼方法可以在Rails的查找程序中使用虛擬屬性作爲條件?Ruby on Rails |條件中的虛擬屬性
例如:
Friend.find(:first, conditions: { full_name: 'Chandler Bing' })
Friend.where(login: '[email protected]', password: 'secret')
# `full_name' and `password' are virtual attributes
感謝。
有什麼方法可以在Rails的查找程序中使用虛擬屬性作爲條件?Ruby on Rails |條件中的虛擬屬性
例如:
Friend.find(:first, conditions: { full_name: 'Chandler Bing' })
Friend.where(login: '[email protected]', password: 'secret')
# `full_name' and `password' are virtual attributes
感謝。
什麼是虛擬屬性?不支持數據庫字段的屬性?
然後你不能那樣做。
虛擬屬性通常不會在數據庫中保留。它們是在保存記錄期間或從數據庫獲取記錄之後進行計算的。那麼你不能這樣做!
我在最近的項目中使用類似的東西。我用它來選擇在某個日期範圍內的記錄。我不使用查找器,而是使用範圍。
scope :since, lambda {|from, to| {:conditions => {:created_at => (from .. to)}}}
這被稱爲然後像Model.since from, to
其中Model
字段的created_at
抵抗給出的範圍檢查。
要爲虛擬屬性執行此操作,您必須在範圍內創建虛擬字段。類似於first_name和last_name字段上的匹配以在全名上創建匹配