Ruby on Rails & Mongomapper : wrong number of arguments (2 for 1)

74 Views Asked by At

I am new to ruby on rails.I am trying to search brokers,whose name contains "Jam" but its giving me error of "wrong number of arguments (2 for 1)". Following is my code:

@brokers = Broker.where("firstName = ?", "Jam")

Why am i getting wrong number of arguments error?

3

There are 3 best solutions below

1
RAJ On BEST ANSWER

As you are using MongoMapper, you may need to use all. You can try following query:

@brokers = Broker.all(firstName: "Jam")

OR

@brokers = Broker.where(firstName: "Jam").all

Source: http://mongomapper.com/documentation/plugins/querying.html

Update:

To use like behavior, you can use regexp such as:

@brokers = Broker.all(firstName: /Jam/)
0
Akshay On
@brokers = Broker.where(firstName: "Jam")
6
Francesco Belladonna On

You should enclose it in array:

@brokers = Broker.where(["brokers.firstName = ?", "Jam"])

That being said, we need to know your rails version (and ruby version). However if you are not interested in using LIKE, you can just do

@brokers = Broker.where(firstName: "Jam")

ActiveRecord has some sql-builder built within (and supports arel if you want to), which allows you to write Brokers.where(hash_key: value) and it will convert it to SELECT * FROM brokers WHERE hash_key = value, so you can write simple queries in a faster way.

The version you posted is not working because where accepts a single string, an array or an hashmap, doesn't accept multiple params.

Update 1 (after discovering you are using mongomapper):

After discovering that you are using mongomapper, which is very different from a default Rails installation (be careful if you are new, lot of stuff won't apply to you, Rails by default uses activerecord), I believe you have to add all at the end of your call, like they do in this question. So something like:

@brokers = Broker.where(firstName: "Jam").all

Also notice that this way of querying won't work with mongomapper: (at least by checking documentation)

@brokers = Broker.where(["brokers.firstName = ?", "Jam"])

So you are forced to use the one with where(firstName: "Jam")

Update 2 (how to perform query similar to SQL LIKE):

If you want to let code behave in a similar fashion like SQL LIKE, as you are requesting in comments, you are able to use regexp, so something like:

@brokers = Broker.where(firstName: /.*Jam.*/)