Reputation: 398
I have a search bar which works fine but it produces a duplicate every time it shows the correct result.
if params[:nav_search]
@art = Art.where(["style_number LIKE ? OR name LIKE ?", "%#{params[:nav_search]}%", "%#{params[:nav_search]}%"]).page(params[:page]).per_page(18)
end
Any clue where I'm going wrong?
Upvotes: 0
Views: 45
Reputation: 7777
Try to the following
@art = Art.where(["style_number LIKE ? OR name LIKE ?", "%#{params[:nav_search]}%", "%#{params[:nav_search]}%"]).distinct.page(params[:page]).per_page(18)
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.
You can see this Rails Guide
for very well understand
Upvotes: 1
Reputation: 1
Use uniq
or distinct
to avoid duplicate records. In your case, you should use distinct
:
if params[:nav_search]
@art = Art.where(["style_number LIKE ? OR name LIKE ?", "%#{params[:nav_search]}%", "%#{params[:nav_search]}%"]).distinct.page(params[:page]).per_page(18)
end
Upvotes: 0
Reputation: 828
include .uniq
try this,
if params[:nav_search]
@art = Art.where(["style_number LIKE ? OR name LIKE ?", "%#{params[:nav_search]}%", "%#{params[:nav_search]}%"]).uniq.page(params[:page]).per_page(18)
end
Upvotes: 0