#112 Anonymous Scopes

本文介绍了一种使用动态范围和匿名作用域来改进高级搜索表单条件逻辑的方法。通过 ActiveRecord 的 scoped 方法,可以灵活地生成带有条件的查询,这些条件可以根据用户输入的关键词、价格范围和类别进行调整。
The scoped method allows you to generate named scopes on the fly. In this episode I show how to use anonymous scopes to improve the conditional logic which was used in the previous episode on advanced search form.
# config/initializers/global_named_scopes.rb
class ActiveRecord::Base
named_scope :conditions, lambda { |*args| {:conditions => args} }
end

# models/search.rb
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
FormData {} [[Prototype]] : FormData append : ƒ append() length : 2 name : "append" arguments : [异常:TypeError: &#39;caller&#39;, &#39;callee&#39;, and &#39;arguments&#39; properties may not be accessed on strict mode functions or the arguments objects for calls to them at get arguments (<anonymous>) at append.invokeGetter (<anonymous>:3:28)] caller : (…) [[Prototype]] : ƒ () [[Scopes]] : Scopes[0] delete : ƒ delete() length : 1 name : "delete" arguments : [异常:TypeError: &#39;caller&#39;, &#39;callee&#39;, and &#39;arguments&#39; properties may not be accessed on strict mode functions or the arguments objects for calls to them at get arguments (<anonymous>) at delete.invokeGetter (<anonymous>:3:28)] caller : (…) [[Prototype]] : ƒ () [[Scopes]] : Scopes[0] entries : ƒ entries() forEach : ƒ forEach() length : 1 name : "forEach" arguments : [异常:TypeError: &#39;caller&#39;, &#39;callee&#39;, and &#39;arguments&#39; properties may not be accessed on strict mode functions or the arguments objects for calls to them at get arguments (<anonymous>) at forEach.invokeGetter (<anonymous>:3:28)] caller : (…) [[Prototype]] : ƒ () [[Scopes]] : Scopes[0] get : ƒ () getAll : ƒ getAll() length : 1 name : "getAll" arguments : [异常:TypeError: &#39;caller&#39;, &#39;callee&#39;, and &#39;arguments&#39; properties may not be accessed on strict mode functions or the arguments objects for calls to them at get arguments (<anonymous>) at getAll.invokeGetter (<anonymous>:3:28)] caller : (…) [[Prototype]] : ƒ () [[Scopes]] : Scopes[0]
10-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值