#migration data
class CreateStats < ActiveRecord::Migration
def self.up
create_table :stats do |t|
t.integer :points
t.integer :assists
t.integer :blocks
t.integer :turnovers
end
def self.down
drop_table :stats
end
end
#Model
class Stat < ActiveRecord:Base
end
How i can store integer data type and when application display the data back (Since it will do calculation) it will display float on each column points, assists, blocks and turnovers?
How i can store integer data type and when application display the data
back
(Since it will do calculation) it will display float on each column
points,
assists, blocks and turnovers?
This seems to be a basic Ruby question. See the following IRB session:
Here is my situation,
In the database, I have a stats table which has:
points (Integer datatype)
assists (Integer datatype)
blocks (Integer datatype)
turnovers (Integer datatype)
In rails, I have stat model
Now If I want to display value from stats table, I can do this
@stats = Stat.find(:all)
It will display all integer value that user entered (Note: User ONLY allowed to enter integer value)
For example, I have these data in stats table
Pointsassistsblocksturnovers
1 4 5 1
5 2 5 5
7 3 2 7
Now, I want to average each column and assign it to stat class
The problem I see, when I assigning to average value to @average_stat, the value get converted to integer. I want to have float value. How I can assign float value in stat class?
If @average_stat is Stat.new then @average_stat.points,
@average_stat.assists, etc... are also integer. So you could use a
array variable, after stats = Stat.find(:all) :
@average_stat=[ stats.sum('points') / stats.count('points'),
stats.sum('assists') / stats.count('assists') , stats.sum('blocks') /
stats.count('blocks') , stats.sum('turnovers') /
stats.count('turnovers') ] .
In fact you shoud use directly average(stat.points), etc.. See
http://api.rubyonrails.org/classes/ActiveRecord/Calculations/ClassMethods.html#M002188