【问题标题】:Rails view, undefined method `empty?' for a datetime objectRails 视图,未定义的方法“空?”对于日期时间对象
【发布时间】:2016-11-27 07:21:31
【问题描述】:

所以我正在修改我的索引视图,使其仅基于名为字段的实例变量呈现特定字段,但是当我这样做时,它工作得很好,除了生成错误的日期时间字段。示例:undefined method empty?' for Tue, 22 Nov 2016 23:01:00 +0000:DateTime 这是查看代码。

<p id="notice"><%= notice %></p>

<h1>Articles</h1>

<table>
  <thead>
    <% @fields = ["headline", "content","date", "locale", "classification" ]  unless @fields.present? %>
    <tr>
      <% @fields.each do |field| %>
        <th><%= "#{field.titleize}" %></th>
      <% end %>
    </tr>
  </thead>

  <tbody>
    <% @articles.each do |article| %>
      <tr>
        <% @fields.each do |field| %>
        <td><%= simple_format article.send(field) %></td>
        <% end %>
        <td><%= link_to 'Show', article %></td>
        <td><%= link_to 'Edit', edit_article_path(article) %></td>
        <td><%= link_to 'Destroy', article, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

<br>

<%= link_to 'New Article', new_article_path %>

这是模型代码

class Article
  include Mongoid::Document
  validates :classification,
    :inclusion  => { :in => [ 'unclassified', 'medical', 'non medical'] }
  validates :headline, presence: true
  validates :content, presence: true
  field :headline, type: String
  field :content, type: String
  field :classification, type: String
  field :weak_classification, type: String
  field :locale, type: String
  field :date, type: DateTime
end

我该如何解决这个问题?

【问题讨论】:

    标签: ruby-on-rails datetime view erb


    【解决方案1】:

    之前可以将字段转换为string

    <%= simple_format article.send(field).to_s %>
    

    或者最好检查一个字段的类型并格式化它。

    def format_article_field(field)
      value = article.send(field)
    
      if value.kind_of?(DateTime)
        value.to_s(:short) # any format shortcut here
      else
        simple_format(value.to_s)
      end
    end
    
    <%= format_article_field field %>
    

    【讨论】:

      猜你喜欢
      • 2014-07-17
      • 1970-01-01
      • 1970-01-01
      • 2016-12-11
      • 2015-08-23
      • 2015-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多