Question

I'm using RoR and mysql database. I want to convert timestamp column to string, so i have the SQL:

@books = Book.find_by_sql("select id, name, date_format(borrow_date, '%m/%d/%Y') borrow_date from books")
@books[0].borrow_date  => 'Sun, 03 Aug 2014 17:00:00 PDT -07:00'

When i output the borrow_date like @books[0].borrow_date, i got un-formatted string 'Sun, 03 Aug 2014 17:00:00 PDT -07:00' which is not expected. I want "08/03/2014"

If i change alias name that different than the column name, i get expected data string.

@books = Book.find_by_sql("select id, name, date_format(borrow_date, '%m/%d/%Y') borrow_date_other from books")
@books[0].borrow_date_other  => "08/03/2014"

I don't want to format date string in ruby code since i need to pull the same data from oracle database and just want to convert to string before use.

Why RoR doesn't allow same column name and alias name? Do i miss something? Thank you in advance.

Was it helpful?

Solution

You are actively loading Books from the database, so AREL tries to map your select statement to the model. In this case, it maps the date to the borrow_date attribute and converts it into a Date object. The original formatting you selected is then no longer relevant as it was parsed to an object which has its own rules for printing the date.

Your second select works since there probably is no attribute of that name on your Book model, so it cannot be mapped to a specific type, so plain String is used.

You could simply add a function like formatted_borrow_date to your model or use a helper to have it format the borrow_date using ruby methods to avoid the hardcoded SQL and date formatting.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top