2016-07-25 263 views
0

背景Rails的輸出不正確

我有我的Rails應用程序的故事的典範。模型的其中一個部分是「已發佈」的布爾值。

在創建和編輯表單上,我有一個切換按鈕,如果故事發布則顯示「開」,如果未發佈則顯示「關」。此切換功能目前正常工作,並且可以切換髮布或未發佈的故事;;並且該切換器相應地更新數據庫。

問題

在節目頁面我試圖if語句做的,但它並沒有解決正確,所以我只是做了一個打印出已發佈的變量,它總是打印出「假「即使在檢查數據庫時它被設置爲」true「。

守則

<% @title="Stories" %> 

<p><strong><%= @story.heading %></strong></p> 

<p><%= @story.body %></p> 

<p> 
    <%= #!!!!!!!!!!!!!!!!Not working currently!!!!!!!!!!!!! 
     # if @story.published 
     # @publish_Notice = "This story has been made public." 
     # else 
     # @publish_Notice = "This story is private." 
     # end 
     # @publish_Notice 

     @story.published # Always prints out 'false' even when database shows 'true' 
    %> 
</p> 

<p>~ <%= @story.authorName %></p> 

<p>Submitted: <%= @story.created_at.strftime("%B, %d %Y") %><br/> 

<%= 
    @location = " " 

    if @story.locationCity == "" || @story.locationCity == " " || @story.locationCity.nil? 
    @location = " " 
    else 
    @location = "Near: " @story.locationCity + ", " + @story.locationState 
    end 
%> 
<%= @location %></p> 

<% if (user_signed_in?) && (current_user == @story.user) %> 
    <%= link_to 'Edit', edit_story_path(@story) %> | 
    <%= link_to 'Delete', @story, method: :delete, data: { confirm: 'Are you sure?' } %> | 
<% end %> 
<%= link_to 'Back', stories_path %> 
+0

其中哪一行是你面臨的問題? – uzaif

+0

@uzaif,我在打印出版信息時遇到了問題。我在我的代碼中註明了問題出在哪裏。 –

回答

1

答案 後的試圖找出並解決這個問題我自己,而不是想出什麼,終於在這裏張貼問題2天后,我發現問題幾分鐘後,在我的故事控制器中的代碼片段。看看你是否可以在我的代碼下面找到問題。

舊代碼

def show 
    if @story.published = false && @story.user != current_user 
    redirect_to stories_url, notice: 'That action is not permitted.' 
    end 
end 

說明

我建立這個代碼片斷,以阻止人們能夠在瀏覽器中的一個故事號碼進入,看到它,即使它WASN沒有發表。問題代碼位於第二行,我查看了故事是否已發佈。我只放了一個等號,因此每次顯示一個故事時,它都會在不更改數據庫的情況下將發佈的變量更改爲「假」。我添加了額外的等號,現在它都可以正常工作。這是新的代碼。

新代碼

def show 
    if @story.published == false && @story.user != current_user 
    redirect_to stories_url, notice: 'That action is not permitted.' 
    end 
end 

謝謝那些誰的追問跟進信息,以幫助我與我的問題這麼快。感謝您的協助。

+1

錯過一個'='可能會造成很多麻煩。 – Pramod

+0

偉大的工作人! – uzaif

+1

'if @ story.published && ...'可能會更好地爲您服務。或者甚至可以在'visible_to'方法中隱藏所有「被髮布」和「是這個作者」邏輯的「@ story.visible_to(current_user)'。 –