2011-11-02 11 views

उत्तर

108

ActiveRecord मानक तरीका का उपयोग करना:

MyModel.where(MyModel[:created_at] < 2.days.ago) 
: अरेल पर एक simple thin layer का उपयोग

MyModel.where(MyModel.arel_table[:created_at].lt(2.days.ago)) 

:

MyModel.where("created_at < ?", 2.days.ago) 

अंतर्निहित Arel इंटरफ़ेस का उपयोग करना

पुस्तकालय squeel का उपयोग करना:

MyModel.where { created_at < 2.days.ago } 
+0

धन्यवाद! अगर मुझे MyTable1 से सभी रिकॉर्ड्स की आवश्यकता है जो एक ही शर्त पर माईटेबल के साथ एक से एक संबंध है, तो क्वेरी कैसे लिखें? मैं 'MyTable1.where (MyTable [: made_at] Sayuj

+0

हां मैंने संबंध सक्रिय रिकॉर्ड क्लास सेट किया है। – Sayuj

-25

Time.now या यह बहुत ही दूसरा अभी को दर्शाता है। इसलिए सभी उपयोगकर्ताओं को खोजने के लिए इससे पहले कि अभी सिर्फ

@users = User.all 

इस का उपयोग सभी उपयोगकर्ताओं से पहले अभी मिलेगा और भविष्य उपयोगकर्ताओं या उन है कि में शामिल होने को बाहर निकाल देगा Time.now

+1

टाइम.now आज जैसा नहीं है –

0

एक और तरीका है में एक गुंजाइश बनाने के लिए है के बाद MyModel या ApplicationRecord में Arelकी तरह इंटरफ़ेस tokland तो जैसे his answer में sugensted का उपयोग कर: दायरे से

scope :arel, ->(column, predication, *args) { where(arel_table[column].public_send(predication, *args)) } 

उदाहरण उपयोग:

MyModel.arel(:created_at, :lt, 2.days.ago) 

सभी पूर्वानूमानों के लिए, documentation या source code की जाँच करें। यह दायरा where श्रृंखला को तोड़ता नहीं है। इसका मतलब है कि आप यह भी कर सकते हैं:

MyModel.custom_scope1.arel(:created_at, :lt, 2.days.ago).arel(:updated_at, :gt, 2.days.ago).custom_scope2 
संबंधित मुद्दे