1

私のアプリケーションは飲み物モデルで構成されています

class Drink < ActiveRecord::Base

  attr_accessible :name
  has_many :recipe_steps, :dependent => :destroy
  has_many :ingredients, through: :recipe_steps
end

成分モデル

class Ingredient < ActiveRecord::Base
  attr_accessible :name

  has_many :recipe_steps
end

ユーザーが食材を検索すると、その食材を含むすべての飲み物が返されるようにするにはどうすればよいですか?

追加情報: 現在、検索に sunspot/solr を使用しています。

4

2 に答える 2

1

まず、Ingredientモデルに次の行が必要です。

has_many :drinks, through: :recipe_steps

関係を定義しますhas_many, through:RecipeStepにも次の行があることを確認してください。

belongs_to :ingredient
belongs_to :drink

次に、次のようなことができますDrinksController

def search
  term = params[:search]
  ingredient = Ingredient.where(:name => term)
  @drinks = Ingredient.find(ingredient).drinks
end

フォームは次のようになります。

<%= form_for @drink, :url => { :action => "search" } do |f| %>
  <%= f.text_field :search %>
<% end %>

すべての名前をすべて知っているわけではありませんが、これでうまくいくはずです。

于 2013-02-19T04:59:33.430 に答える
0

以下はうまくいくはずです:

class Ingredient < ActiveRecord::Base
  ...
  has_many :recipe_steps
  has_many :drinks, through: :recipe_steps
end
于 2013-02-19T04:51:38.943 に答える