简体   繁体   中英

filter active record results in ruby

Im completely new to Ruby on Rails. Im working on an existing API and I have a sql query which is executed with:

results = ActiveRecord::Base.connection.select_all(query)

The output of the results is:

{"availability"=>"In Stock", "available_to_purchase"=>1}
{"availability"=>"Void", "available_to_purchase"=>0}
{"availability"=>"Out of Stock", "available_to_purchase"=>0}
{"availability"=>"In Stores Only", "available_to_purchase"=>0}

I know want to get all values for availability based on available_to_purchase being 0. I have tried:

res = results.where(available_to_purchase: 0)

But I get an error saying:

undefined method `where'

I also tried:

res = results.select { |result| result.available_to_purchase == 0 }

But i end up with the error:

undefined method `available_to_purchase'

I know I can loop through and check available_to_purchase is 0, then add to a new array. But is there any method to quickly filter active record results based on value of a column?

Going directly through the connection avoids nearly everything ActiveRecord is intended to provide you. First thing, read Active Record Basics . The Rails guides are really well put together and should contain everything you need for your first few weeks using the framework.

The reason you aren't getting the where method you expected is that it's a method on ActiveRecord::Relation , and select_all just returns you a list of hashes. By the time you call results.where , it's too late. You need to instantiate a Product model (or whatever would match your table name), which is as simple as:

class Product < ActiveRecord::Base
end

Rails will look at the products table (again, I'm making up your table name) for the attributes a Product has, and then you'll be able to query based on them with where :

results = Product.where(available_to_purchase: 0)

The model will also have the accessor methods you were trying for, so you can do things like results[0].available_to_purchase == 0 or results[0].availability = 'Already in your house' .

In order to call .where on the results, you need an instance of an active record relation. Regular ActiveRecord queries will return this. select_all, however, returns an array of hashes. Array does not have the method where.

res = results.select { |result| result.available_to_purchase == 0 }

Your second error is because you are attempting to access ruby hash keys incorrectly. Properties must be accessed as result['available_to_purchase']

Here is the answer to your question. I do agree with others though that you should be using ActiveRecord .

results.select { |result| result['available_to_purchase'] == 0 }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM