Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在RubyonRails中格式化时间和日期_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails 在RubyonRails中格式化时间和日期

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服务器时出

运行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服务器
时出现了一个错误:

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。您有两个
终止一个单元格,但缺少终止的
。我不同意在
方法上创建的
格式,格式和显示问题实际上与模型无关。一个一致格式化日期的视图助手…哦,是的,没错。我没有在那里思考。