views:

36

answers:

2

I need to perform these SQL below, but I couldn't get the result.

newid=Header.find_by_sql(
  "SELECT coalesce(max(transaction_id),0)+1 AS id 
  FROM transaction_headers 
  WHERE transaction_year = #{Time.now.year} AND 
  transaction_type='#{fields[:transaction_type]}'"
)

But I can't seem to get the result to newid. The only value I got was [#<Header>] Anyone can help me to create the correct statement for Ruby?

EDIT: Table fields

-----------------------------------------------------------------------------------
| transaction_type | transaction_year | transaction_id | customer_id | uid | date |
-----------------------------------------------------------------------------------

Thank you.

+1  A: 

You are getting a Header object (which will be populated with an id), so I think in your case newid.id will actually give you the id you're looking for, or if you want an array of these values do:

headers = Header.find_by_sql(...)
header_ids = headers.collect(&:id)

HTH

rainkinz
Thank you. I think I've been one step forward. I tried that, and I got the Header object, but when I try to collect I got [nil, nil, nil]. I am sure the query is correct. It should return 1 field with name id. Any idea?EDIT: I have added table fields
Magician
rainkinz
Oh.. okay.. thanks.. will try it now.Actually the primary keys are those transaction_id, transaction_type, and transaction_year. And Ruby kept sending ORDER clause by those keys, and remove the transaction_type field conditions. So I had to resort to manual SQL.
Magician
A: 

What you are getting back from the find is an Array of Header objects.

headers = Header.find_by_sql(...)
newid = headers.first.id

I might ask myself why I need the id though

Bryan Ash
I've tried that, and got nil instead.
Magician
Rails convention dictates that the primary key be called `id`. If you're creating tables from scratch, I'd strongly recommend you stick with convention.
Bryan Ash
I can't.. My primary key consists of 3 keys, transaction_id, transaction_year, and transaction_type. I'll have a lot of id, and that would be confusing for which ID is which.
Magician
I wish you luck ... but then, you have magic on your side, so probably don't need it ;-)
Bryan Ash
LOL. These are few of my tableshttp://stackoverflow.com/questions/3220000/ruby-on-rails-multiple-composite-primary-keys-questionSo using id will be very confusing. But thank you for your hint :D
Magician