Reputation: 901
In an attempt to better learn Rails and I'm building a simple Blackjack game, but I'm running into a problem of storing the variable. I understand how to store user-genereated data into the db using form_for, but I'm struggling to create a random number and put it in the db.
@hand = rand(9) + 2
I have "hand" as a field in my db, just curious how to store this random number. Any help anyone could provide to point me in the right direction would be very much appreciated. Thanks.
Upvotes: 2
Views: 1292
Reputation: 13972
Here's some example code:
@game = Game.find(42)
@game.hand = rand(9) + 2
@game.save
In this case, I'm assuming that Game
is a model in your Rails application. Fields (or "database columns", if you prefer) in the games
table you can access and set by using their names - so we're saving our rand
value into a field named hand
.
(Of course, you have to create that field first - either by having created it via some scaffolding, or by creating a database migration to add that column).
Likewise, to read back the hand
variable.
@game = Game.find(42)
@game.hand
Upvotes: 3