2016-07-07 102 views
0

初學者警報!
我在我的user#show視圖中有此IF聲明。我查了一下,如果在鐵軌控制檯任何職位user_id:7,它返回的結果,但是當我看着http://localhost:3000/users/7,我無法看到評論:無法從我的if!= nil語句獲得正確的結果

您沒有任何職位呢。繼續發帖!

<% @posts.each do |post| %> 
<% if @posts != nil %> 
<%= link_to "#{post.title}", post_path(post) %> 
<% else %> 
<p> You don't have any post yet. Keep posting! </p> 
<% end %> 
<% end %> 

誰能幫助我?謝謝!

回答

0

我想你需要的是:

<% if @posts.present? %> 
    <% @posts.each do |post| %> 
    <%= link_to "#{post.title}", post_path(post) %> 
    <% end %> 
<% else %> 
    <p> You don't have any post yet. Keep posting! </p> 
<% end %> 
+0

是的,首先'@ posts'可能會返回一個空數組,並且在Ruby中[]!= nil' – oreoluwa

+0

即空數組不等於0 – oreoluwa

+0

第二個通過'@ posts'的循環應該已經嵌套檢查是否存在帖子 – oreoluwa

0

如果變量@posts是空的,你不能讓<p> You don't have any post yet. Keep posting! </p>

User.find(7).posts將返回一個陣列。 an empty array != nil

試試這個:

<% if [email protected]? %> 
    <% @posts.each do |post| %> 
    <%= link_to "#{post.title}", post_path(post) %> 
    <% end %> 
<% else %> 
    <p> You don't have any post yet. Keep posting! </p> 
<% end %> 
+2

'除非... ...否則是end'主要在Ruby社區皺起了眉頭。而是使用'if ... else ... end' – oreoluwa

+1

你是對的。我改變了我的回答 –

+0

@孫悟空,我不會讓別人的個人喜好影響你的代碼。如果它讀得很好並且可以維護,請保留它。在這種情況下,我會選擇'<%除非@ posts.empty? %>'或'<如果@posts%>'。 – Tass