Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: get the first n active record objects of a model

I need a way to get the first n items of a model. Item.first(n), Item.all[1..n] will do that, except they return an array, not an object. How do I get it as an ActiveRecord Object?

irb(main):135:0> Player.where(game_id: 1).class
=> Player::ActiveRecord_Relation    #Ok
irb(main):136:0> Game.first.players.class
=> Player::ActiveRecord_Associations_CollectionProxy    #Ok
irb(main):137:0> Player.where(game_id: 1).first(2).class
=> Array   #Not Ok

I want to run update_all on the returned collection of players, and I can't do that on an array.

like image 227
Life4ants Avatar asked Jan 04 '17 18:01

Life4ants


People also ask

What is ActiveRecord object Rails?

1 What is Active Record? Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.

What is ActiveRecord in Ruby on Rails?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

What is pluck in Ruby?

ruby rails. Rails has a great, expressive term called pluck that allows you to grab a subset of data from a record. You can use this on ActiveRecord models to return one (or a few) columns. But you can also use the same method on regular old Enumerables to pull out all values that respond to a given key.


1 Answers

You do .limit(n)

Combine this with .offset and you have pagination.

like image 69
max pleaner Avatar answered Sep 28 '22 08:09

max pleaner