Reputation: 926
I'm new to Rails. I'm using Rails 3.2.13. I'll try to keep my question succinct:
In my controller, I want to get the last 10 entries from the Observation table. I have:
def index
@times = Observation.select(:load_time).last(10)
end
In that view, I attempt to render the 10 entries in @times
like this:
<% @times.each do |time| %>
<p>time: <%= time %></p>
<% end %>
A response I get in my web page looks like this:
time: #<Observation:0x007fe22bf2a138>
I'm wondering how to get the actual time variable as a float rather than (what looks like) a memory address. It appears that the last 10 entries are correctly making it to the controller which is good.
There is no logic in my Observation < ActiveRecord::Base class because the migration is responsible for defining the schema. Here's what my db/migrate/create_observations.rb looks like:
class CreateObservations < ActiveRecord::Migration
def change
create_table :observations do |t|
t.float :load_time
t.timestamps
end
Thanks in advance for any help - it's much appreciated.
Upvotes: 2
Views: 369
Reputation: 21785
You just have to access the variable inside the object
<%= time.your_field %>
in your case:
<%= time.load_time %>
Upvotes: 2
Reputation: 4603
In your view, <%= time =>
translates to _buf << time.to_s
(where _buf
is ERb's internal output buffer). An easy workaround to this is to define Observation#to_s
, like so:
class Observation < ActiveRecord::Base
def to_s
load_time.to_s
end
end
Be aware that a Observation.select(:id).map(&:to_s)
now would cause an ActiveModel::MissingAttributeError
error (since to_s
requires this column to be present).
In general, I'd adwise to explicitly fetch the result you need, i.e. in your case:
<% @times.each do |time| %>
<p>time: <%= time.load_time %></p>
<% end %>
Upvotes: 1