我正试图通过Rails中的简单搜索来搜索标题/正文。但是当我试图将匹配的字符串放在title / body中时,它无法显示期望的结果。你能帮我检查一下吗?提前谢谢你
article.rb
def self.search(query)
# where(:title, query) -> This would return an exact match of the query
where("title LIKE ? or body LIKE ?", "%#{query}%", "%#{query}%")
end
控制器
if params[:search]
@articles = Article.search(params[:search])
#@articles = Article.where(["title || body like ?","%#{params[:search]}%"])
else
@articles = Article.all
end
显示
<%= form_tag(articles_path, :method => "get", id: "search-form") do %>
<%= text_field_tag :search, params[:search], placeholder: "Title or body" %>
<button class="btn btn-success-outline" type="submit">Search</button>
请在github链接获取详细信息:https://github.com/khoinguyen91/CoderSchool_blog
答案 0 :(得分:1)
好的,快速浏览一下GitHub上的其余代码,问题是here:
def index
#@articles = Article.all
if params[:search]
@articles = Article.search(params[:search])
#@articles = Article.where(["title || body like ?","%#{params[:search]}%"])
else
@articles = Article.all
end
@markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML)
if params[:tag]
@articles = Article.tagged_with(params[:tag])
else
@articles = Article.all
end
end
在检查params[:search]
后,您需要检查params[:tag]
,当您从搜索表单提交时,该@articles
将为空白。这意味着@articles = Article.all
只会被完整的文章列表(ExpectedException
)替换。