2012-12-06 43 views
1

我在过去曾问过类似问题,但认为我可能错误地回答了问题。根据当前对象ID生成搜索结果

我想知道是否有可能在rails中通过对象的show动作获取当前属性,然后针对该属性执行搜索功能。例如

def show 
@recipe = Recipe.find(params[:id]) 
end 

在配方模型有一个属性

:dish_name 

这改变这取决于配方我在看,所以说我想列出类似于当前dish_name是食谱显示在显示页面上,我将如何去解决这个问题?只是在正确的方向寻找一些指针。我曾看过solr,但决定坚持搜索功能的快速搜索功能,尽管我无法在ransack中找到实现此目的的方法。有没有人为此类方法编写过类似方法?

BBC食物做同样的事情,如果不一样,我想实现

http://www.bbc.co.uk/food/recipes/easy_chocolate_cake_31070 

如果你看看右边你会看到一个名为相关食谱节

任何帮助表示赞赏

回答

1

我不认为你真的需要这样的快速搜索,你可以使用ActiveRecord's query methods。我建议在Recipe其获取相关食谱创建一个实例方法related_recipes,像这样:

class Recipe < ActiveRecord::Base 

    ... 

    def related_recipes 

    # take the recipe's dish name and split it at spaces, 
    # then wrap each item in the resulting array with '%' 
    # to create SQL query terms. 
    # e.g. "italian pasta" becomes ["%italian%", "%pasta%"] 
    terms = dish_name.split(' ').map { |t| "%#{t}%" } 

    # create a scope with all recipes except this one 
    others = self.class.where('id != ?', id) 

    # return all recipes other than this one that contain any of the terms 
    # e.g. for the dish "italian pasta", this will become: 
    # others.where('dish_name LIKE ? OR dish_name LIKE ?', '%italian%', '%pasta%') 
    return others.where(terms.map { 'dish_name LIKE ?' }.join(' OR '), *(terms)) 
    end 

然后在你的show操作,可以获取相关的食谱是这样的:

def show 
    @recipe = Recipe.find(params[:id]) 
    @related_recipes = @recipe.related_recipes 
end 

可以通过遍历@related_recipes来显示结果。我已经大量评论过上述内容,但如果没有任何意义,请在评论中告诉我。

+0

谢谢你的回答,所以为了理解这里发生了什么,terms = @ recipe.dish_name.split('')将会拆分正在显示的dish_name,所以每次都会依赖于recipe ID ? – Richlewis

+0

我已经更新了我的答案,因为我意识到你确实不需要为这种类型的东西使用ransack。 –

+0

为了回答你的问题,'split'将'dish_name'作为你所在页面的配方('@ recipe.dish_name'),并将它拆分为空格,所以“italian pasta”变成数组''italian “,”面食“]'。然后它将每个术语都包含在'%'s中,在SQL语言中这意味着“匹配包含这个术语的任何东西”。然后,您可以将其传递给'where'以获取包含任一术语的所有*其他*食谱。 –

相关问题