2012-03-02 70 views
0

我有一些控制器 - 用戶,類別,故事和註釋。一切都很好,直到我做了評論。在我的數據庫中,我想保存內容,user_id,story_id,但表格是空的。 @ comment.save是錯誤的。這裏是我的代碼部分:rails無法將結果保存在數據庫中

CommentsController:

def create 
    @story = Story.find(params[:story_id]) 
    @comment = @story.comments.create(params[:comment]) 
    if @comment.save 
    flash[:success] = "Successfull added comment" 
    redirect_to stories_path 
    else 
    render 'new' 
    end 
end 

show.html.erb爲StoriesController:

<b><%= @story.title %></b> <br/><br/> 

<%= @story.content %> <br/><br/> 

<% @story.comments.each do |comment| %> 
    <b>Comment:</b> 
    <%= comment.content %> 
<% end %> 

<%= form_for([@story, @story.comments.build]) do |f| %> 
    <div class="field"> 
    <%= f.label :content %><br /> 
    <%= f.text_area :content %> 
    </div> 
    <div class="actions"> 
    <%= f.submit "Add" %> 
    </div> 
<% end %> 

在StoriesController我做同樣的事情,但我現在不知道如何做到這一點。

def create 
    @categories = Category.all 
    @story = current_user.stories.build(params[:story]) 
end 
+0

哪一行明確導致錯誤假的?你是否在故事和評論之間建立了聯繫? – ellawren 2012-03-02 23:33:14

+0

我不知道如何,但當我重新啓動服務器的錯誤消息的問題已修復,但評論表我DB是空的。我在story.rb has_many:評論和評論.rb - belongs_to:故事。在route.rb我: 資源:故事做 資源:評論 結束 – user1107922 2012-03-03 00:11:06

+0

現在我再次有錯誤消息..這行:@comment = current_user.comments.create(PARAMS [:評論]) – user1107922 2012-03-03 00:21:03

回答

1

的錯誤:「爲無未定義的方法:NilClass」似乎總是要咬我,當我假設它沒有在模型/類已被實例化。如果你上線了以下錯誤:

@comment = current_user.comments.create(params[:comment]) 

我猜想,你的代碼正在沒有登錄的用戶,因此CURRENT_USER爲零運行。您@comment代碼的結構表明你只打算讓註冊用戶創建的意見,所以你可以試試這個方法:

if current_user 
    @comment = current_user.comments.create(params[:comment]) 
else 
    redirect :root, :notice => "Sorry you must be registered and logged in to comment" 
end 

希望這有助於。

+0

變更它是如何編寫的,但當我登錄時,問題仍然存在。並且錯誤消息位於此行,您猜測。 – user1107922 2012-03-03 12:01:38

0

我很愚蠢!我錯過了用戶模型中的has_many註釋..但現在問題仍然存在,因爲註釋的內容無法保存在數據庫中,表中的Comments是空的。

@ comment.save是在我的情況

def create 
    @story = Story.find(params[:story_id]) 
    if current_user 
    @comment = current_user.comments.create(params[:comment]) 
    end 

    if @comment.save 
    flash[:success] = "Successfull added comment" 
    redirect_to story_path(@story) 
    else 
    render 'new' 
    end 
end 
+0

需要嘗試的一些事情:1)確保爲註釋添加了user_id列和belongs_to語句2)邏輯問題:當第一個if語句失敗時,@comment變量不會被創建,第二個if語句的條件將生成異常。 3)確保你所有的註釋字段都是attr_accessible--檢查開發日誌,看看你是否得到這個警告。 4)在代碼中手動創建一個測試註釋並嘗試保存它(不要使用... create(params [:comment])5)puts()到服務器控制檯params [:comment]看看你的表單正在發回給你。 – 2012-03-03 17:51:01