2016-02-01 50 views
0

我想創建一個幫助器方法,將顯示{user.name} has no submitted posts."用戶的個人資料顯示視圖,如果他們還沒有提交任何帖子,並顯示他們有多少帖子。目前在我的節目視圖中,我有<%= render @user.posts %>,當有0個帖子提交時,它不顯示任何內容。幫助程序方法檢測後發表評論

部分的職位是:

<div class="media"> 
    <%= render partial: 'votes/voter', locals: { post: post } %> 
    <div class="media-body"> 
    <h4 class="media-heading"> 
     <%= link_to post.title, topic_post_path(post.topic, post) %> 
     <%= render partial: "labels/list", locals: { labels: post.labels } %> 
    </h4> 
    <small> 
     submitted <%= time_ago_in_words(post.created_at) %> ago by <%= post.user.name %> <br> 
     <%= post.comments.count %> Comments 
    </small> 
    </div> 
</div> 

香港專業教育學院的嘗試:

def no_post_submitted?(user) 
     user.post.count(0) 
     "{user.name} has not submitted any posts yet." 
    end 

我的用戶顯示的看法:

<%= if no_post_submitted?(@user) %> 
<%= render @user.posts %> 

其即時通訊超過肯定是錯誤的,但我有不知道如何實現這個方法。

回答

3

如果你正在使用render @user.posts你可以添加一個簡單的條件:

<% if @user.posts.empty? %> 
    <p><%= @user.name %> has no submitted posts</p> 
<% else %> 
    <%= render @user.posts %> 
<% end %> 

世上本沒有多大意義了這個創造了幫手,除非你需要在多個地方使用它。

+0

非常感謝你這並獲得成功。我想,但由於某種原因,我認爲製作一個輔助方法會使這個更容易,但不是真的。 –

0

在Ruby方法自動返回的最後一個值,因此這種方法:

def no_post_submitted?(user) 
    user.post.count(0) 
    "{user.name} has not submitted any posts yet." 
end 

總是會返回一個字符串 - 如果你使用一個字符串中的條件文本將被評估爲真與警告warning: string literal in condition。這也不是你如何使用count - 傳遞0將導致它查詢列0或只是錯誤。

所以修復你會做的方法:

def no_post_submitted?(user) 
    user.posts.empty? 
end 

但是,這種條件是如此簡單,它並沒有真正保證一個輔助方法。相反,你會這樣寫:

<%= if user.post.any? %> 
    <%= render @user.posts %> 
<% else %> 
    <%= "{user.name} has not submitted any posts yet." %> 
<% end %> 
1

渲染集合返回nil,如果集合是空的,所以你可以使用||運營商:

<%= render @user.posts || "{@user.name} has not submitted any posts yet." %> 

或者,如果有更多的代碼,使另一部分:

<%= render @user.posts || render 'no_posts' %> 
0

有一對夫婦與您的解決方案的問題。請記住,rails更多的是關於約定而不是配置。

您的方法no_post_submitted?實際上應該返回true/false,因爲它的方法以?結尾。爲了清晰起見,它應該被命名爲no_posts_submitted?。它應該是這個樣子:

def no_post_submitted?(user) 
    user.posts.count > 0 
    end 

那麼,應該有另一種輔助方法將打印您所需的信息,喜歡的東西:

def no_posts_message(user)  
    "{user.name} has not submitted any posts yet." 
end 

,最終你都可以將其插入這樣的:

<% if no_posts_submitted?(user) %> 
<%= no_posts_message(user) %> 
<% else> 
<%= render @user.posts %> 
<% end %> 
0
作爲

docs

如果集合爲空,則渲染將返回nil,因此提供替代內容應該相當簡單。

<h1>Products</h1> 
<%= render(@products) || "There are no products available." %> 

-

所以......

<%= render(@user.posts) || "#{@user.name} has not submitted any posts yet." %>