1

過去に似たようなことを質問したことがありますが、質問の言い方が間違っていたのではないかと思います。

レールでオブジェクトの表示アクションを介して現在の属性を取得し、その属性に対して検索機能を実行できるかどうかを知りたいです。例えば

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

レシピモデル内には属性があります

:dish_name

これは、どのレシピを見ているかによって変わるので、ショーページに表示されている現在の料理名に似たレシピをリストしたいとします。どうすればよいでしょうか? 正しい方向へのいくつかの指針を探しているだけです。私はsolrを見てきましたが、検索機能のためにランサックに固執することに決めましたが、ランサックでこれを達成する方法がわかりません..誰かが以前にこのような方法を書いたことがありますか?

BBCの食べ物は、私が達成したいことと同じではないにしても、似たようなことをします

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

右側を見ると、関連レシピと呼ばれるセクションが表示されます

任意の助けをいただければ幸いです

4

1 に答える 1

1

これには実際にランサックが必要だとは思いません。ActiveRecordのクエリメソッドを使用するだけです。次のように、関連するレシピをフェッチするインスタンス メソッド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。私は上記に重くコメントしましたが、何か意味をなさない場合は、コメントでお知らせください。

于 2012-12-06T09:01:52.420 に答える