【发布时间】:2013-02-12 13:51:02
【问题描述】:
我正在尝试做的事情: 我有一个模型“Recipe”,在其中我定义了一个“search”方法,该方法从复选框中获取一组字符串(我称它们为标签),并且单个字符串。这个想法是在数据库中搜索包含字符串的“名称”或“指令”中包含任何内容的食谱,并且还具有与它的“标签”属性匹配的任何标签。
问题:搜索方法返回我数据库中的所有食谱,并且似乎根本无法通过特定参数查找。
控制器中的动作方法:
def index
@recipes = Recipe.search(params[:search], params[:tag])
if !@recipes
@recipes = Recipe.all
end
respond_to do |format|
format.html
format.json { render json: @recipe }
end
end
我的模型中的搜索方式:
def self.search(search, tags)
conditions = ""
search.present? do
# Condition 1: recipe.name OR instruction same as search?
conditions = "name LIKE ? OR instructions LIKE ?, '%#{search[0].strip}%', '%#{search[0].strip}%'"
# Condition 2: if tags included, any matching?
if !tags.empty?
tags.each do |tag|
conditions += "'AND tags LIKE ?', '%#{tag}%'"
end
end
end
# Hämtar och returnerar alla recipes där codition 1 och/eller 2 stämmer.
Recipe.find(:all, :conditions => [conditions]) unless conditions.length < 1
end
任何想法为什么它返回所有记录?
【问题讨论】:
-
是的,这绝对是真的。如果你有更好的例子,请赐教。这就是我到目前为止的想法。
-
您的标签是如何在参数中返回的?作为数组还是字符串?如果它们只是一个字符串,您可能必须先对它们运行
split()。 -
我很确定这是一个字符串数组,例如 ["meat", "fish"]。
标签: ruby-on-rails search methods