I'm trying to build a basic search where only the entire exact search term shows results. Currently it is showing results based on individual words.
Here's the code from the model:
def search
find(:all, :conditions => ['term' == "%#{search}%"])
end
Sorry in advance. I'm very new to rails!
Thank you.
Remove the % from "%#{search}%"
so it's "#{search}"
.
%
is a wildcard that matches every result containing the word. So "%tea%"
for example would match tear, nestea, and steam, when that's not what you want.
This should yield an exact match:
def search find(:all, :conditions => ['term' == "#{search}"]) end
Your code doesn't work for several reasons.
search
will always be nil
. ['term' == "%#{search}%"]
condition doesn't make much sense because - as I said before - search
is undefined and therefore the condition will is the same as ['term' == "%%"]
. The string term
is not equal to %%
therefore the whole condition is basically: [false]
. I would do something like this:
# in your model
scope :search, -> (q) {
q.present? ? where("column_name LIKE :query", query: "%#{q}%") :none
}
# in your controller
def set_index
@b = Best.search(params[:search]).order(:cached_weighted_score => :desc)
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.