处理视图中的nil(即@ post.author.name中的nil作者)

Ray*_*ard 2 ruby null views ruby-on-rails

我想展示作者的姓名; <% @post.author.name %>除非作者为零,否则有效.所以我要么使用unless @post.author.nil?或者添加一个检查nil的author_name方法<% @post.author_name %>.我试图避免后者.

问题是我可能需要根据是否有值来添加/删除单词.例如,如果我只显示nil,则"发布于1/2/3 by"将是内容.如果作者是零,我需要删除"by".

Max*_*yak 6

空对象模式是避免这种情况的一种方法.在你的班上:

def author
  super || build_author
end
Run Code Online (Sandbox Code Playgroud)

这样你无论如何都会得到一个空作者.但是,由于您实际上并不希望在预期时有空对象nil,因此您可以使用某种类型的演示者.

class PostPresenter
  def initialize(post)
    @post = post
  end

  def post_author
    (@post.author && @post.author.name) || 'Anonymous'
  end
end
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用try,@post.author.try(:name)如果你可以习惯它.