我不认为你真的需要为此洗劫,你可以使用ActiveRecord
's query methods。我建议创建一个获取相关食谱的实例方法,如下所示related_recipes
:Recipe
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
。我已经对上述内容进行了大量评论,但如果有任何不妥之处,请在评论中告诉我。