Reputation: 13
I'm trying to searching the title/body with simple search from Rails. But when I tried to put the matched string in title/body, it cannot display the expect result. Could you please help me have a check? Thank you in advance
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
controller
if params[:search]
@articles = Article.search(params[:search])
#@articles = Article.where(["title || body like ?","%#{params[:search]}%"])
else
@articles = Article.all
end
show
<%= 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>
Please get details at github link : https://github.com/khoinguyen91/CoderSchool_blog
Upvotes: 0
Views: 54
Reputation: 66263
OK, took a quick look at the rest of your code on GitHub and the problem is 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
After checking for params[:search]
you're checking for params[:tag]
which will be blank when submitting from your search form. This means that @articles
just gets replaced with the full list of articles (@articles = Article.all
).
Upvotes: 1