0

Is it possible to perform type conversion in rails when we load data from database. I am trying to fetch some fields which are currently as datetime in database, I want them as date or time depending on the need in the application. I do not want to do the conversion in Controller or View as after some time the fields will get fixed in the database. If this can be handled in the Model?

4

1 回答 1

0

As far as I understand you have one datetime attribute and you want to display it alternatively as date and as time depending on the situation

You could implement two methods in your model for example if you have Post model it would look like this

class Post
  attr_accessible :updated_at

  def updated_at_date
    updated_at.to_date # or whatever formatting you want to apply to it
  end 

  def updated_at_time
    updated_at.to_time # or whatever formatting you want to apply to it
  end 
end

And in your controllers and views you will call updated_at_date or updated_at_time depending on the situation.

Later, when you change the data storage logic, you won't need to change any code in your app except the code inside the two methods inside your model

于 2013-08-25T14:21:25.940 回答