سؤال

أعلم أنه يمكنك إنشاء نطاقات مسماة في القضبان، والتي تتيح لك تحديد الشروط التي يمكن بعد ذلك بناؤها لاحقا:

named_scope :active, :conditions => {:active => true}

...

MyModel.active.find(...)

يعمل هذا عن طريق إنشاء كائن وكيل لم يتم تقييمه حتى وقت لاحق. ما أريد أن أعرفه هو إذا كان من الممكن إنشاء ديناميكية الأمم المتحدةاسمه النطاق؟

التي أقصدها، هل هناك طريقة "فو" التي يمكنني الذهاب إليها

scope = MyModel.foo(:conditions => {:target_id => 4})

ثم تمر scope حول ككائن وكيل يمكنني القيام به أكثر .finds أو غيرها من المكالمات المبشرة؟

هل كانت مفيدة؟

المحلول

نعم، تحقق نطاقات مجهولة:

def find_products
  scope = Product.scoped({})
  scope = scope.conditions "products.name LIKE ?", "%#{keywords}%" unless keywords.blank?
  scope = scope.conditions "products.price >= ?", minimum_price unless minimum_price.blank?
  scope = scope.conditions "products.price <= ?", maximum_price unless maximum_price.blank?
  scope = scope.conditions "products.category_id = ?", category_id unless category_id.blank?
  scope
end
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top