代码之家  ›  专栏  ›  技术社区  ›  dangerousdave

需要一个空字符串,但在rubyonrails中得到一个异常

  •  1
  • dangerousdave  · 技术社区  · 16 年前

    控制器

    @articles = current_user.articles
    

    看法

    <% @articles.each do |article| %>
      <%= link_to "#{article.title} , #{article.author.name}" articles_path%>
    <% end %>
    

    有时文章没有作者,所以在数据库中为null,这会导致以下错误

    你有一个零的对象,当你没想到! 计算nil.name时出错

    6 回复  |  直到 16 年前
        1
  •  4
  •   Simone Carletti    16 年前

    将新实例方法添加到 Article 模型。

    class Article
      def title_and_author
        returning "" do |s|
          s << title
          s << ", " << author.name if author.name?
        end
      end
    end
    

    那么在你看来

    <% @articles.each do |article| %>
      <%= link_to article.title_and_author, articles_path %>
    <% end %>
    
        2
  •  2
  •   Cimm    16 年前

    <% @articles.each do |article| %>
      <%= link_to (article.author ? "#{article.title} , #{article.author.name}" : article.title), articles_path %>
    <% end %>
    

    使用简短的if/else形式。如果作者存在,则打印标题;如果作者不存在,则只打印标题。

        3
  •  2
  •   shingara    16 年前

    try 方法

    <% @articles.each do |article| %>
      <%= link_to "#{article.title} , #{article.author.try(:name)}" articles_path%>
    <% end %>
    
        4
  •  2
  •   vise    16 年前

    另一个解决方案:

    <% @articles.each do |article| %>
      <%= link_to [article.title, article.author.try(:name)].reject{ |obj| obj.nil? }.join(', ') articles_path %>
    <% end %>
    

        5
  •  1
  •   Steve Weet    16 年前

    如果您可能在应用程序中的许多地方遇到这个问题,您可能希望通过添加以下方法之一来修改模型类

    def name
      d = read_attribute(:name)
      d.nil? ? " " : d
    end
    

    在数据库中插入空白而不是空值

    def before_save
      self.name = " " if self.name.nil?
    end
    

    或者,您可以创建一个helper方法,根据名称是否存在来构建链接文本,如下所示

    def link_text(title, name)
      if name.blank?
        title
      else
        "#{title} , #{name}"
    end
    
        6
  •  1
  •   Slobodan Kovacevic    16 年前

    我会创建一个围绕链接的助手。比如:

    def link_to_article(article)
      if article.author.nil?
        link_to "#{article.title}", article_path(article)
      else
        link_to "#{article.title} , #{article.author.name}" article_path(path)
      end
    end
    
    # and in view simply do:
    <%= link_to_article(article) %>
    
        7
  •  1
  •   David    6 年前

    <%= link_to [article&.title, article&.author&.name].compact.join(",") articles_path %>
    
    推荐文章