How can I use the find Rails method to execute an AND or OR query?

Suppose I have a model called "product." Suppose a product has three fields. These fields are "name" (type string), "value" (integer type) and "is_visible" (bool type).

1) How can I perform a search query using the "find" Rails method (if there is another method, that's fine) so that I can search all products with a value of more than 100 And is_visible right?

2) What if we want to change this for a search, where is the name! = '' OR cost == 0?

This is not a problem for SQL, but I would like to think that Rails has the ability to make AND / OR queries to the database without using SQL.

Thanks!

+5
source share
3 answers

You will need to use the conditions parameter for the find method. The condition parameter can be either a hash, or an array, or a string. There are many options for conditions, so I recommend reading the API reference . For example, if you want (1):

Product.find(:all, :conditions => ['cost > ? and is_visible is true', 100])

Or 2)

Product.find(:all, :conditions => ["name != '' or cost =0])
+13
source

If you want something like LINQ, you can check out alternative Ruby ORMs like DataMapper or Sequel that provide more sophisticated filtering capabilities.

For example, in Sequel 2 you can write:

items.filter((:cost > 100) & (:is_visible = 1))

You can also use the bitwise "|" operator to get the OR condition.

In DataMapper, it will look like this:

Model.all(:cost.gt => 100, :is_visible.eq => 1)

, Symbol.

+4

This is exactly the problem SQL was designed to solve, so why not use it? Just add the appropriate condition: your problem is resolved.

0
source

All Articles