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.
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? 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.
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.
You do .limit(n)
Combine this with .offset
and you have pagination.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With