我希望能够通过URL传递参数,只返回与搜索查询匹配的文档而不是所有记录。我如何获得"原型"传递给我的zip.rb文件中的self.all方法的参数?
Rails输出:
Started GET "/?page=2&per_page=200&prototype[state]=NY" for ::1 at 2016-04-03 12:31:58 -0400
Processing by ZipsController#index as HTML
Parameters: {"page"=>"2", "per_page"=>"200", "prototype"=>{"state"=>"NY"}}
paginate({"page"=>"2", "per_page"=>"200", "prototype"=>{"state"=>"NY"}, "controller"=>"zips", "action"=>"index", "sort"=>{}})
getting all zips, prototype={}, sort={}, offset=200, limit=200
在上面的rails s输出中,原型参数被捕获在" Parameters" hash和in paginate,但不会从self.all方法流向hash,因为原型是空白的。
zips_controller.rb
def index
args=params.clone #update a clone of params
args[:sort]=get_sort_hash(args[:sort]) #replace sort with hash
@zips = Zip.paginate(args)
@locations = zip_markers @zips
end
zip.rb
def self.all(prototype={}, sort={:population=>1}, offset=0, limit=100)
#map internal :population term to :pop document term
tmp = {} #hash needs to stay in stable order provided
sort.each {|k,v|
k = k.to_sym==:population ? :pop : k.to_sym
tmp[k] = v if [:city, :state, :pop].include?(k)
}
sort=tmp
#convert to keys and then eliminate any properties not of interest
prototype.each_with_object({}) {|(k,v), tmp| tmp[k.to_sym] = v; tmp}
prototype.slice!(:city, :state, :pop) if !prototype.nil?
Rails.logger.debug {"getting all zips, prototype=#{prototype}, sort=# {sort}, offset=#{offset}, limit=#{limit}"}
result=collection.find(prototype)
.projection({_id:true, city:true, state:true, pop:true, loc:true})
.sort(sort)
.skip(offset)
result=result.limit(limit) if !limit.nil?
return result
end
def self.paginate(params)
Rails.logger.debug("paginate(#{params})")
page=(params[:page] ||= 1).to_i
limit=(params[:per_page] ||= 30).to_i
offset=(page-1)*limit
sort=params[:sort] ||= {}
#get the associated page of Zips -- eagerly convert doc to Zip
zips=[]
all(params, sort, offset, limit).each do |doc|
zips << Zip.new(doc)
end
#get a count of all documents in the collection
total=all(params, sort, 0, 1).count
WillPaginate::Collection.create(page, limit, total) do |pager|
pager.replace(zips)
end
end