evilgeniuz
evilgeniuz

Reputation: 376

Rails find method

I want to get an id from the record.

When i write this:

@ticket.table = Table.find(:all, :conditions => {:train => @ticket.train, :datestart => @ticket.selldate})

I suppose it returns amount of the records.

Help me please.

UPD: I have an output:

=> [#<Table id: 6, train: 1, time: "12-00", datestart: "2012-01-10", created_at:
 "2012-01-10 01:59:29", updated_at: "2012-01-10 01:59:29">]

Table id is 6. I need to get it.

Upvotes: 0

Views: 1137

Answers (2)

Bhushan Lodha
Bhushan Lodha

Reputation: 6862

@ticket.table = Table.find(:all, :conditions => {:train => @ticket.train, :datestart => @ticket.selldate}).map(&:id)

will give you array of ids for all your satisfying condition. If you want only one id use the code below.

@ticket.table = Table.find(:all, :conditions => {:train => @ticket.train, :datestart => @ticket.selldate}).map(&:id).first

Hope this helps.

Upvotes: 2

jefflunt
jefflunt

Reputation: 33954

id is just a property on that object. Simply call:

 > @ticket.table.id
=> 6

Assuming that the Table class is a sub-class of ActiveRecord::Base, all objects of this type should have an id attribute that you can just reference with .id

The problem you're having above is that you're using .find(:all, ...) which will always return a collection of objects, even if only one record is found, which is what's causing you to get an array with only one element in it.

Therefore, either use .find(:first, ...) or .find(:all, ..., :limit => 1), to return just one row, or simply reference the first element in the array via one of the following methods:

 > @ticket.table.first.id
=> 6

or

 > @ticket.table[0].id
=> 6

Upvotes: 2

Related Questions