I’m new to rails and am trying to get an understanding on some of the
language usage…I have a mysql database with a table of data…I want
to retrieve the last record in that table without sending it an ‘id’
or anything…I’ve tried the following:
@prevticket = Tankticket.find(:last)
last_net_vol = @prevticket.net_vol
Some problems I see with the above:
Your find syntax is wrong.
@prevticket = Tankticket.last
See the Rails guides for correct query usage:
- Without an ORDER BY clause, getting the first, or last record may not
give you what you might expect.
Databases don’t always guarantee that records are returned in any
specific order. Again, look at the Rails guides to see the SQL generated
by ‘first’ and ‘last’ methods.
If you’re look for a specific record it is safer to specify the ORDER BY
clause. It happens that the last method does specify an ORDER BY.
=> SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
However first does not:
=> SELECT * FROM clients LIMIT 1
In some database this could produce a result you might not expect. For
instance Oracle does not return results ordered by the primary key
without an ORDER BY clause specified explicitly. So Client.first will
give you back a single random row from the table. It will likely NOT be
the one with the smallest ID.
Specify your order explicitly if you really want the record with the
smallest or largest ID:
@prevticket = Tankticket.find(:first, :order => ‘id DESC’)
You should NOT rely on the ordering of the primary key to find
specific records. If you need to ensure that tank tickets are kept in a
specific order then use a list management plugin. Something like
acts_as_list (there are also some enhanced implementations of list
management gems/plugins). Search Github.
Try to use proper, and consistent naming conventions for your class
and table names. Ruby used CamelCase for class names so each word in the
class name should be capitalized.
Tankticket should be TankTicket.
Variable names should use underscores to separate words. They should be
all lower case and avoid abbreviations when non-obvious:
@prevticket should be @previous_ticket
I hope this is helpful and welcome to Rails.