1

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]+'%'])
@[email protected](:all,:conditions =>['city like?', '%bad%'])

I receive the error:

wrong number of arguments (2 for 0..1)

Can anybody explain what is happening?

2 Answers 2

3

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]+'%')
@[email protected]('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%")
Sign up to request clarification or add additional context in comments.

2 Comments

You could also chain these calls together: @herbivores = Deer.where('state like ?', '%' + params[:number] + '%').where('city like ?', '%bad%')
@DanielVandersluis: you could, but that would result in a different result than the OP seemed to want. I'll add that as an additional point though, thanks.
0

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

3 Comments

This approach works, but will call the database many more times than necessary. It's also quite verbose...
@PinnyM I prefer your method but just for my own knowledge am I not right in saying it will only call the database once but will have a larger result set than yours as it is a less defined query (and be a heavier query)?
You are right, this would only hit the database more if 'city' were an association (which is apparently not the case here). But it would have a larger result set, as you said.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.