Eric
Eric

Reputation: 1245

How do I select a certain field from an array of objects of a certain class in Ruby on Rails 2.3.14

If I have an array of 100 objects of a class called Stream, like this:

User.find(1001).streams.find( :all, :order => "id", :limit => 100 )

which is basically a data table, how would I select a certain field, such as rating, from it? In SQL, all I need to do is, SELECT rating FROM streams WHERE user_id=1001 ORDER BY id LIMIT 100, but I don't know how to do that in Ruby on Rails. Using the command above returns all the fields, which I can't use.

Upvotes: 0

Views: 1079

Answers (1)

Harish Shetty
Harish Shetty

Reputation: 64363

Code below will return an array of rating

User.find(1001).streams.all( :order => "id", :limit => 100).map(&:rating) 

If you want to avoid the cost of retrieving all attributes of the User object:

User.find(1001).streams.all:select => "rating", 
  :order => "id", :limit => 100).map(&:rating) 

You can use the standard SELECT clause syntax in the value for the key :select.

If you want to avoid constructing User objects:

User.connection.select_values("select rating from users order by id limit 100")

Upvotes: 1

Related Questions