views:

42

answers:

1

Hi,

This is my current code

@descriptions = TableName.find(:first, :conditions=> ["table_id = ?", table_name.table_id], :order => 'author_year')

author_year column contains data of

kannan 1845

kohlun 1976

palani 1956

Using above code, it gives result with order of author_year based on author names. I need to order the query ascendingly based on the year which presents in author_year. and I wish to print the oldest data based on the year not ordered by author name. Kindly give me some suggestion on this issue.

+1  A: 

Option 1: store in the format "year author" instead

Option 2: store author and year in different columns and sort by year

Option 3: add a "year" column and do:

In the console (rails 2.X right?):

script/generate migration add_author_yr_to_table_name author_yr:integer

(Ensure you have a migration that contains something like: add_column :table_names, :author_yr, :integer)

Migrate the DB:

rake db:migrate

In your table_name.rb file (TableName is the name of the class right?):

before_save :extract_year

def extract_year
  self.year = author_year.last(4)
end

And then sort by "year"

Edited to explain step by step.

jordinl
I wish to use third option. Other options I cant take other options and I dont have permission to do.
Palani Kannan
At first, I tried "def author_yr "#{self.author_year.last(4)}" end". I feel both are same. But it shows "Undefined local variable or method 'author_yr'" when i use author_yr in find by ":order => ["author_year like = ?", author_yr]". Please correct 'find' statement to order correctly.
Palani Kannan
have you added am author_yr column to the table?
jordinl
No, Can you suggest me the way to include in table and sort by year?
Palani Kannan
edited the original answer...
jordinl