Mohammad Sadiq Shaikh
Mohammad Sadiq Shaikh

Reputation: 3200

How to modify active record query result attribute value in Rails 3

I am having query

@users = User.all

@users contains name, created_at, email, mobile etc as attribute values

I want to update the created at to user readable format from mysql datetime format and update it in controller

I have written the code to convert date to human readable format but don't know how to set value to the attribute before it goes to view

So any method will be appriciated

Upvotes: 1

Views: 1346

Answers (3)

DGM
DGM

Reputation: 26979

Rails can add additional date/time formats... put something like this in an initializer file:

Date::DATE_FORMATS[:short_date] = "%b %d, %Y"
Date::DATE_FORMATS[:short_slashed] = "%m/%d/%Y" #careful when giving this to mysql adapter
Date::DATE_FORMATS[:date_dashed] = "%m-%d-%Y"
Date::DATE_FORMATS[:mysql_date] = "%Y-%m-%d"
Date::DATE_FORMATS[:full_date] = "%A, %B %d, %Y"
Time::DATE_FORMATS[:short_slashed] = "%m/%d/%Y %I:%M %p"
Time::DATE_FORMATS[:mytime] = "%a %b %d at %I:%M %p"
Time::DATE_FORMATS[:short_date] = "%b %d, %Y"
Time::DATE_FORMATS[:date_dashed] = "%m-%d-%Y"
Time::DATE_FORMATS[:mysql_date] = "%Y-%m-%d"

and then in your view, you can choose any of them:

 @user.created_at.to_s(:mytime) 
 @user.created_at.to_s(:short_date) 

documentation

Upvotes: 3

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230306

Messing with attribute values just for the sake of presentation - bad idea, don't do that.

This looks like a helper method. I'd probably put it into User model itself (make_human_date contains your logic of "humanizing" the date, which you haven't specified)

# model
class User
  def human_created_at
    make_human_date(created_at)
  end
end

# view
<%= @user.human_created_at %>

Alternatively, you can make a real helper method, because it only aids presentation, it's not part of business logic.

# helper
module MyControllerHelper
  def human_created_at user
    make_human_date(user.created_at)
  end
end

# view
<%= human_created_at(@user) %>

Upvotes: 2

John H
John H

Reputation: 2488

Use strftime() directly on the created_at attribute in the view:

@user.created_at.strftime("%D")

Docs: http://www.ruby-doc.org/core-1.9.3/Time.html#method-i-strftime

Upvotes: 2

Related Questions