2016-11-27 46 views
0

所以我修改我的索引視圖,以使其僅基於名爲字段的實例變量呈現特定的字段,但是當我這樣做時,它工作得很好,除了生成錯誤的日期時間字段。例如:undefined method empty?' for Tue, 22 Nov 2016 23:01:00 +0000:DateTime這裏是視圖代碼。Rails視圖,未定義的方法`空?'對於日期時間對象

<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 %> 
相關問題