我正在尝试在 rails 中搜索我的 postgresql 数据库。我遵循了Railscasts #111 Advanced Search教程,它以纯文本形式处理我的项目列的名称和类别。但是,我也想为我的搜索设置一个最低/最高价格,这也是我遇到问题的地方。在我的数据库中,我的价格以“AU $49.95”格式存储为字符串。我可以在我的范围搜索中将它转换成一个浮点数吗?如果有怎么办?如果没有,我该怎么办?
这是代码:
搜索.rb
class Search < ActiveRecord::Base
attr_accessible :keywords, :catagory, :minimum_price, :maximum_price
def items
@items ||= find_items
end
private
def find_items
scope = Item.scoped({})
scope = scope.scoped :conditions => ["to_tsvector('english', items.name) @@ plainto_tsquery(?)", "%#{keywords}%"] unless keywords.blank?
scope = scope.scoped :conditions => ["items.price >= ?", "AU \$#{minimum_price.to_s}"] unless minimum_price.blank?
# scope = scope.scoped :conditions => ["items.price <= ?", "AU \$#{maximum_price.to_s}"] unless maximum_price.blank?
scope = scope.scoped :conditions => ["to_tsvector('english', items.catagory) @@ ?", catagory] unless catagory.blank?
scope
end
end
search_controller.rb
class SearchesController < ApplicationController
def new
@search = Search.new
end
def create
@search = Search.new(params[:search])
if @search.save
redirect_to @search, :notice => "Successfully created search."
else
render :action => 'new'
end
end
def show
@search = Search.find(params[:id])
end
end
感谢您阅读到这里!