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?
1 に答える
0
私が理解している限り、datetime属性が1つあり、状況に応じて日付と時刻として交互に表示したい
たとえば、Post モデルがある場合、モデルに 2 つのメソッドを実装できます。これは次のようになります。
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
また、コントローラーとビューでは、状況に応じて updated_at_date または updated_at_time を呼び出します。
後でデータ ストレージ ロジックを変更する場合、モデル内の 2 つのメソッド内のコードを除いて、アプリ内のコードを変更する必要はありません。
于 2013-08-25T14:21:25.940 に答える