我正在尝试在我的rails应用程序中构建一个过滤器,它使用url参数,并根据模型中的方法(根据几个不同的标准返回true或false )返回记录,而不是直接检查数据库。不过,我还是有些问题。
下面是我的模型中的代码
def action_required?
true unless (self.nap_correct? && self.claimed? && self.duplicates == "")
end在我看来,我有一个使用params过滤结果的链接。下面是代码
<%= link_to "All Messages", url_for(:action_required => true) %>在我的控制器里
if params[:action_required].blank?
@citations = @client.citations.paginate(:page => params[:page], :per_page => 50).order("id desc")
else
@citations = @client.citations.where(:action_required => true).paginate(:page =>[:page], :per_page => 50).order("id desc")
end现在它给了我这个错误
SQLite3::SQLException: no such column: citations.action_required: SELECT "citations".* FROM "citations" WHERE "citations"."client_id" = ? AND "citations"."action_required" = 't'这里我漏掉了什么?
发布于 2015-08-18 02:00:23
首先,您不需要编写true unless...,只需这样做
def action_required?
self.nap_correct? && self.claimed? && self.duplicates == ""
end然后将您的复杂条件转换为scope
scope :action_required, ->(){
self.where(nap_correct: true, claimed: true, duplicated: '')
}然后,您可以使用作用域:
@citations = @client.citations.action_required.paginate(:page =>[:page], :per_page => 50).order(id: :desc)如果您的#nap_correct?或claimed?方法也是复杂的Ruby方法,并且不仅仅是模型中的字段,那么您也需要将它们提取到SQL中(例如,创建scopes)。
还有一种更简单的方法:用.select(&:action_required)替换where -它将使用Ruby Array方法来选择记录(所以选择是在Ruby中完成的,而不是在数据库中-因此它会更慢)。而且您还必须手动处理分页,因为paginate将期望在其上运行查询的ActiveRecord::Relation,而不是Ruby Array。
https://stackoverflow.com/questions/32056765
复制相似问题