2013-09-22 147 views
0

我有一些代碼是應該被覈查是否存在屬性的方法調用,它似乎既不是如果要不回來是什麼...如果respond_to?不返回任何東西

%h2= @post.title 
    .row      
     .col-sm-12 
      = render "blog_meta", :post => @post 
      #text_body 
       = @post.content 
      %hr 
      - if @post.comments.count > 0 
       %h2 Comments 
       #comments 
        - @post.comments.where(:original_id => nil).each do |comment| 
         .comment 
          .profile 
           %img{:src => "/assets/profile_image_sample.jpg"} 
          .message 
           .username 
            - if comment.user.respond_to?('username') 
             .username= comment.user.username 
            - else 
             .username= comment.user.first_name 
           = comment.content 
           - logger.info "LOGGER--->>" + comment.user.first_name 
           .reply-link 
            %a{:href => "#"} Reply to Comment 
         - if comment.replies.count > 0 
          - nesting = 0 
          - comment.replies.each do |comment| 
           = render "comment", :comment => comment, :nesting => nesting 
       %hr 
      = render "submit_comment" 

但是,如果我只是= comment.user.first_name沒有條件語句,然後它工作正常..

+0

或者你可以將這種方法添加到你的'User'模型'def名稱;用戶名||名字;結束「,那麼你可以在你的視圖上調用'user.name'。 – j03w

回答

2

最有可能的user響應usernameblanknil。你可能會想這樣做,而不是

- if comment.user.username.blank? 
     .username= comment.user.first_name 
    - else 
     .username= comment.user.username 

respond_to用於檢查的方法爲對象定義。如果爲對象定義了方法,它將返回true。它不關心該方法的輸出是什麼。

+0

非常感謝你,通常用於迴應什麼? – Melbourne2991

+1

更新了答案 – tihom

+2

一個簡短的代碼風格評論。使用符合'!'符號的條件通常會更好。所以在這樣的情況下,你只需切換'if'和'else'塊並刪除'!'。如果你沒有'else'塊,只需使用'unless'。 – Almaron