I am having trouble with some code inside an application I am working on.
With the following code:
#herbivores=Deer.find(:all,:conditions =>['state like?', '%' + params[:number]+'%'])
#herbi=#herbivores.find(:all,:conditions =>['city like?', '%bad%'])
I receive the error:
wrong number of arguments (2 for 0..1)
Can anybody explain what is happening?
Use the query API to keep the correct scope, and also do this more cleanly since where is chainable:
#herbivores=Deer.where('state like ?', '%' + params[:number]+'%')
#herbi=#herbivores.where('city like ?', '%bad%')
You can also chain these directly without an intermediate variable:
#herbi = Deer.where('state like ?', "%#{params[:number]}%").where('city like ?', "%bad%")
Or you can merge it into one method call:
#herbi = Deer.where('state like ? AND city like ?', "%#{params[:number]}%", "%bad%")
I believe what is happening is that you are treating #herbivores like its a model that you can find on, but it is an Array of Deer records so is not a model.
EDIT:
Purhaps you want:
#herbivores=Deer.find(:all,:conditions =>['state like ?', "%#{params[:number]}%"])
#herbivores.each do |herbi|
if herbi.city == 'bad'
puts "bad city in state #{ani.state}"
end
end
Related
So I want to my user to be able to search by title and description so I have added this line of code.
Here is the error i receive
wrong number of bind variables (1 for 2) in: title LIKE ? or
description LIKE ?
def index
#posts = Post.where(["title LIKE ? or description LIKE ?", "%#{params[:search]}%"]).page(params[:page]).per(10)
end
You can name your arguments when you use the hash syntax - for example name it just :q:
#posts = Post
.where('title LIKE :q or description LIKE :q', q: "%#{params[:search]}%")
.page(params[:page]).per(10)
you're using two ? in this statement. so, the interpreter is expecting 2 arguments for each ?.
change your code to this:
#posts = Post.where("title LIKE ? OR description LIKE ?", "%#{params[:search]}%", "%#{params[:search]}%").page(params[:page]).per(10)
Let me know if it helps.
It's good practice to check Case insensitive matching
#posts = Post.where("LOWER(title) LIKE ? OR LOWER(description) LIKE ?", "%#{params[:search].downcase}%", "%#{params[:search].downcase}%").page(params[:page]).per(10)
You can also use this gem called ransack. Although is focused on forms, you can still make great simple search queries. See this documentation: https://github.com/activerecord-hackery/ransack/wiki/Basic-Searching
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.
You do not pass any value to that method. Therefore search will always be nil.
The ['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].
Rails 5.0 uses a different syntax for queries. The syntax you used is very old and doesn't work anymore.
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
I have this tentative search function, however, it is limited to search one chunk of keyword only.
def self.search(search)
search_condition = "%" + search + "%"
active.where("lower(title) LIKE ?", search_condition.downcase)
end
E.g. I have this title: "Peter Paul Mary"
If I search "peter Mary", it doesn't show.
I found this code useful in this post:
def self.search(search)
if search
search_length = search.split.length
find(:all, :conditions => [(['name LIKE ?'] * search_length).join(' AND ')] + search.split.map { |name| "%#{name}%" })
else
find(:all)
end
end
Unfortunately, it's in older rails.
So, how do I translate this into rails 4?
Update:
I've changed to something like this:
def self.search(str)
search = str.split.map{|w| "(lower(title) LIKE ? )"}.join(" OR ")
values = str.split.map{|w| "%#{w.downcase}%"}.map(&:inspect).join(', ')
.where("#{search}", values)
end
But it raises this error:
ActiveRecord::PreparedStatementInvalid (wrong number of bind variables (1 for 2) in: (lower(title) LIKE ? ) OR (lower(title) LIKE ? )):
Please advise.
If you happen to be using Postgres with your app, then you can easily take advantage of PG's Full Text Search capabilities using the pg_search gem.
You can also plug into frameworks like Solr or ElasticSearch to give you this functionality, but they will increase you development effort.
PG and MySQL both also have pattern matching functions that would allow you to search based on a regex string from the search values.
So I have a search box working in my application, however it only returns a result if the search matches exactly what is submitted, as opposed to something like it. Heres my code for the search method;
def self.search(search)
if search
where(:title => ["title LIKE ?", "#{search}"])
else
all
end
end
The "title LIKE ?" doesn't seem to be returning results which are like the query, only ones which are exactly the same.
What am I missing here?
Try this
where(["title LIKE ?", "%#{search}%"])
Here is another way if you want to avoid string queries (using arel):
where(arel_table[:title].matches("%#{search}%"))
I am doing what I thought was something very simple - finding a user and incrementing an integer.
#user = User.where("created_at > ?", Time.now.midnight).select(:visit_count)
#user.visit_count += 1
#user.save(:validate=>false)
I get the following error:
undefined method `visit_count' for [#<ActiveLink visit_count: 1>]:ActiveRecord::Relation
This seems like a Rails 3 thing - where am I going wrong?
Your query always returns multiple results as an Array.
Just add .first to be sure that you only pick the first result.
#user = User.where("created_at > ?", Time.now.midnight).select(:visit_count).first
If you want to update many records at the same time, look at update_all method :
http://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-update_all