Ruby on rails 在RubyonRails中格式化时间和日期
运行rails c这项功能:Ruby on rails 在RubyonRails中格式化时间和日期,ruby-on-rails,ruby,Ruby On Rails,Ruby,运行rails c这项功能: 2.2.3 :002 > Post.find(1).created_at.strftime("Posted on %B %d, %Y at %H:%M") Post Load (0.7ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = $1 LIMIT 1 [["id", 1]] => "Posted on October 23, 2015 at 15:31" 但是运行rails服务器时出
2.2.3 :002 > Post.find(1).created_at.strftime("Posted on %B %d, %Y at %H:%M")
Post Load (0.7ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = $1 LIMIT 1 [["id", 1]]
=> "Posted on October 23, 2015 at 15:31"
但是运行rails服务器
时出现了一个错误:
index.html.erb where line #28 raised:
Object must be a Date, DateTime or Time object. "Posted on October 26, 2015 at 11:44" given.
index.html.erb看起来像:
<%- model_class = Post -%>
<table class="table table-striped">
<thead>
<tr>
<th><%= model_class.human_attribute_name(:created_at) %></th>
</tr>
</thead>
<tbody>
<% @posts.each_with_index do |post, index| %>
<tr>
<td><%=l post.created_at.strftime("Posted on %B %d, %Y at %H:%M") %>
</td>
</td>
</tr>
<% end %>
</tbody>
看起来问题只是代码开头的一个零散的
l
这应该起作用:
<%= post.created_at.strftime("Posted on %B %d, %Y at %H:%M") %>
更好的做法是将这次的格式设置移到一个模型上,并在post上调用它。并将“postedon”移到方法之外。因此:
<td> Posted on <%= post.formatted_created_on %> </td>
发布在
我建议您在网站上创建一个lool。仅供参考,您的.erb不包含有效的HTML。您有两个
终止一个单元格,但缺少终止的
。我不同意在方法上创建的格式,格式和显示问题实际上与模型无关。一个一致格式化日期的视图助手…哦,是的,没错。我没有在那里思考。