crashbangboom wrote:
> 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:
> 
> def get_last_net_vol
>        @prevticket = Tankticket.find(:last)
>       last_net_vol = @prevticket.net_vol
>       return last_net_vol
> end

Some problems I see with the above:

1. Your find syntax is wrong.

    @prevticket = Tankticket.last

See the Rails guides for correct query usage:
http://guides.rubyonrails.org/active_record_querying.html#retrieving-a-single-object

2. 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.

Example:

Client.last
=> SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1

However first does not:

Client.first
=> 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')

3. 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.

4. 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.

http://en.wikipedia.org/wiki/Camelcase

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.
-- 
Posted via http://www.ruby-forum.com/.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to