2010-01-12 70 views
1

我有一个名为Product的模型的Rails应用程序(运行在2.2.2版本上)。产品与特征之间存在着多属性关系。问题是我需要为产品提供搜索功能。所以我需要能够搜索具有相似名称和其他一些属性的产品。棘手的部分是,搜索还必须返回具有搜索表单中指定的一组特定功能的产品(这是由一堆复选框表示的)。下面的代码工作,但它给我的印象相当低效:构建一个拥有和属于多个查询

@products = Product.find(:all, :conditions=>["home=? AND name LIKE ? AND made_by LIKE ? AND supplier LIKE ? AND ins LIKE ?",hme,'%'+opts[0]+'%','%'+opts[1]+'%','%'+opts[3]+'%','%'+opts[4]+'%']) 


#see if any of these products have the correct features 
if !params[:feature_ids].nil? 
    f = params[:feature_ids].collect{|i| i.to_i} 
    @products.delete_if {|x| x.feature_ids!=f} 
end 

我很抱歉,我的轨道把握/ SQL是如此之弱,但没有人有关于如何改进上面的代码有什么建议?非常感谢!

+0

一件事:如果我的回答帮你,请把它标记为回答您的问题(绿色对勾):) 10qu – 2010-01-13 13:49:20

回答

1

首先,我建议你手动编写一个FeatureProduct模型(不使用默认的“has_and_belongs_to_many”) EG

class FeatureProduct 
    belongs_to :feature 
    belongs_to :product 
end 

class Product 
    has_many :feature_products 
    has_many :features, :through => :feature_products 
end 

class Feature 
    has_many :feature_products 
    has_many :products, :through => :feature_products 
end 

对于搜索:您可能会发现宝石SearchLogic是什么你需要。它支持'LIKE'条件(这意味着你可以用更多的'Rails方式'写你的查询)。它还支持使用相关模型的条件执行搜索(更精确地说,在您的特征模型上)。

解决办法是这样的:

search = Product.search 
search.name_like = opt[0] 
search.made_by_like = opt[1] 
... 
search.feature_products_id_equals = your_feature_ids 
.. 
@product_list = search.all 

还有一个excellent screencast解释采用这种宝石。

祝你好运:)

+0

谢谢!实际上我研究了一下SearchLogic,它看起来很棒。然而,它显然不适合我的rails版本(我不允许升级)。 你的回答相当有帮助,但我仍然在计算这里的绳索,所以很抱歉,花了我很长时间才点击箭头。 – Anna 2010-01-14 20:20:37

相关问题