Ruby on rails 逐模型搜索
我的应用程序由一个饮料模型组成Ruby on rails 逐模型搜索,ruby-on-rails,ruby-on-rails-3,ruby-on-rails-3.2,sunspot,Ruby On Rails,Ruby On Rails 3,Ruby On Rails 3.2,Sunspot,我的应用程序由一个饮料模型组成 class Drink < ActiveRecord::Base attr_accessible :name has_many :recipe_steps, :dependent => :destroy has_many :ingredients, through: :recipe_steps end 类饮料:销毁 有很多:配料,通过::配方步骤 结束 成分模型 class Ingredient < ActiveRecord::
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
class成分
当一个用户搜索一种配料时,我该如何让它返回所有含有该配料的饮料
附加信息:我目前正在使用sunspot/solr进行搜索。以下内容可以正常工作:
class Ingredient < ActiveRecord::Base
...
has_many :recipe_steps
has_many :drinks, through: :recipe_steps
end
class成分
以下各项可以正常工作:
class Ingredient < ActiveRecord::Base
...
has_many :recipe_steps
has_many :drinks, through: :recipe_steps
end
class成分
首先,在您的配料
模型中,您需要这一行:
has_many :drinks, through: :recipe_steps
要定义有许多,请通过:
关系。确保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 %>
{:action=>“search”}do | f |%>
我不知道你所有的名字,但这应该能让你走了。首先,在你的
配料
模型中,你需要这一行:
has_many :drinks, through: :recipe_steps
要定义有许多,请通过:
关系。确保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 %>
{:action=>“search”}do | f |%>
我不知道你所有的名字,但这会让你走。我会把搜索方法放在我的饮料控制器中吗?我的表单应该如何进行过滤?目前我的搜索表单由一个带有params[:search]的文本字段组成,这非常有用。。。在过去的4天里,我一直在做这件事。。我的最后一个问题是,如何让我的表在控制器中查看我的索引操作,以便@drinks使用搜索操作中的饮料?因此,您想要一个显示搜索结果的表吗?在
饮料
文件夹中创建一个名为search.html.erb
的视图,在routes.rb(即get”/drinks/search/:search“=>”饮料#search“,:as=>:饮料(search
)中为其创建一条路线,然后在方法中添加一个重定向(到
饮料(search)路径)。然后在视图中,您可以执行类似于@drinks.each do | drink |
等操作。我是否可以将搜索方法放在我的饮料控制器中?我的表单应该如何进行过滤?目前我的搜索表单由一个带有params[:search]的文本字段组成,这非常有用。。。在过去的4天里,我一直在做这件事。。我的最后一个问题是,如何让我的表在控制器中查看我的索引操作,以便@drinks使用搜索操作中的饮料?因此,您想要一个显示搜索结果的表吗?在饮料
文件夹中创建一个名为search.html.erb
的视图,在routes.rb(即get”/drinks/search/:search“=>”饮料#search“,:as=>:饮料(search
)中为其创建一条路线,然后在方法中添加一个重定向(到
饮料(search)路径)。然后在视图中,您可以执行类似于@drinks.each do | drink |
等操作。