Rails模型更改字段

时间:2014-08-25 05:42:39

标签: ruby-on-rails activerecord

我想更改模型中的created_at格式,所以我这样写:

class Mem < ActiveRecord::Base
  def created_at
    DateTime.strptime(created_at, '%d-%m-%Y') 
  end
end

但我得到了

stack level too deep

那我该怎么办?谢谢

4 个答案:

答案 0 :(得分:2)

有很多方法可以访问属性值。这应该有效:

class Mem < ActiveRecord::Base
  def created_at
    DateTime.strptime(attributes['created_at'], '%d-%m-%Y') 
  end
end

答案 1 :(得分:2)

这是因为您调用相同的方法create_at,请尝试:

def created_at
  DateTime.strptime(self[:created_at], '%d-%m-%Y') 
end

你也可以尝试:

def created_at
   DateTime.strptime(super, '%d-%m-%Y') 
end

答案 2 :(得分:1)

重命名您的方法......

self.my_created_at
  ##Jul 05,2014
 created_at.strftime("%b %d,%Y") 
 ##OR July 5th, 2014
 ##created_at.to_date.to_formatted_s(:long_ordinal)
end

并使用它: -

  <%=@user.my_created_at.strftime("%b %d,%Y") %> =>  Jul 05,2014

    <%= @user.my_created_at.to_date.to_formatted_s(:long_ordinal)%> => July 5th, 2014

答案 3 :(得分:0)

def created_at DateTime.strptime(self.created_at, '%d-%m-%Y') end