2016-11-27 8 views
0

私はフィールドビューのインスタンス変数に基づいて特定のフィールドのみをレンダリングするようにインデックスビューを変更していましたが、これを実行すると、エラーを生成するdatetimeフィールドを除いて正常に機能しました。例:undefined method empty?' for Tue, 22 Nov 2016 23:01:00 +0000:DateTimeここにビューコードがあります。Railsビュー、未定義メソッド `empty? ' for datetime object

<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 

ですか?

答えて

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 %> 
関連する問題