扶手:方法与模型链接 [英] Rails: method chaining in model
本文介绍了扶手:方法与模型链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
试图建立在我的模型搜索方法,并加入基于参数传递给方法的条件。然而,没有得到最初的里后链接
Trying to create a search method in my model and join conditions based on arguments passed to the method. However, nothing gets chained after the initial "where"
控制器:
Item.search(args)
型号:
def self.search(args = {})
include ActsAsTaggableOn # Tagging model for search
result = where("title LIKE ? OR description LIKE ? OR tags.name LIKE ?", "%#{args[:search]}%", "%#{args[:search]}%", "%#{args[:search]}%")
.joins("JOIN taggings ON taggings.taggable_id = items.id")
.joins("JOIN tags ON taggings.tag_id = tags.id")
# Categories
if args[:categories]
result.where(:category_id => args[:categories])
end
# Order
if args[:order] == "category"
result.joins(:categories).order("categories.title ASC")
else
result.order("title DESC")
end
# Pagination
result.paginate(:per_page => 10, :page => args[:page])
end
即使我去掉了,如果块,做一个链条直接算账,这是行不通的:
Even if I strip out the if block and do a chain directly afterwards, it doesn't work:
result = where(:foo => "bar")
result.order("name DESC")
...只是运行在那里。
... runs just the where.
任何想法?
感谢提前。
推荐答案
你应该做的是IT连锁通过调整结果的定义
,当您去:
What you should do is chain it by adjusting the definition of result
as you go:
result = result.where(...)
每次必须重新分配回产生与更新的范围。这是因为 result.where
返回一个新的范围,它不会调整现有的范围。
Each time you must re-assign back to result with the updated scope. This is because result.where
returns a new scope, it does not adjust the existing scope.
这篇关于扶手:方法与模型链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文