2016-09-01 68 views
1

我對Ruby相當陌生。我正在嘗試一起創建一個簡單的發佈應用程序的教程。Ruby on Rails創建操作不起作用

我的創建操作不起作用。我試過這個,它似乎在終端中做了一些事情,但它並沒有將它添加到我的Posts對象中。

這裏是我的崗位控制器:

class PostsController < ApplicationController 
    def index 
    @posts = Post.all 
    end 

    def show 
    @post = Post.find(params[:id]) 
    end 

    def new 
    @post = Post.new 
    end 

    def create 
    @post = Post.new(:title => params[:title], :content => params[:content]) 
    @post.save 
    end 

    def edit 
    end 

    def update 
    end 

    def destroy 
    end 
end 

這裏是我的新觀點:

<h1>Add a New Post</h1> 

<%= form_for @post do |f| %> 
    <p> 
    <%= f.label :title %> 
    <%= f.text_field :title %> 
    </p> 
    <p> 
    <%= f.label :content %> 
    <%= f.text_area :content %> 
    </p> 
    <p> 
    <%= f.submit "Add a New Post" %> 
    </p> 
<% end %> 

這是在終端出現,當我嘗試提交:

Started POST "/posts" for ::1 at 2016-08-31 17:54:39 -0700 
ActiveRecord::SchemaMigration Load (16.4ms) SELECT "schema_migrations".* FROM   "schema_migrations" 
Processing by PostsController#create as HTML 
Parameters: {"utf8"=>"✓", "authenticity_token"=>"tGpevHtpEoP5jHYqCn1G7tUKX9YWnx+PWkqlPzKadTCiIEX1UGs96mSCrDf UIShKjp+ObwNA6G1nh3KE5gAIgw==", "post"=>{"title"=>"Jack's Post", "content"=>"Please use this post"}, "commit"=>"Add a New Post"} 
(0.1ms) begin transaction 
SQL (16.0ms) INSERT INTO "posts" ("created_at", "updated_at") VALUES (?, ?) [["created_at", 2016-09-01 00:54:40 UTC], ["updated_at", 2016-09-01 00:54:40 UTC]] 
(14.7ms) commit transaction 
No template found for PostsController#create, rendering head :no_content 
Completed 204 No Content in 114ms (ActiveRecord: 31.3ms) 

我覺得我已經閱讀了大約一百萬個堆棧溢出帖子,似乎沒有人能夠得到答案。任何幫助將非常感激!

回答

0

您已成功將記錄插入數據庫。接下來你想發生什麼?如何:

redirect_to action: 'index' 
1

您應該使用強參數從表單中獲取所需的參數。

class PostsController < ApplicationController 

    def create 
    @post = Post.new(post_params) 
    @post.save 
    end 

private 

    def post_params 
    params.require(:post).permit(:title, :content) 
    # params.require(:post).permit! # Allow all 
    end 

end 

如果你希望你的exisiting解決方案正常工作,您需要前綴PARAMS這樣的:

@post = Post.new(:title => params[:post][:title], :content => params[:post][:content]) 

如果您檢查日誌,你會看到表單輸入嵌套的內部post

"post"=>{"title"=>"Jack's Post", "content"=>"Please use this post"} 
+0

強大的參數可能不通過該OP是繼教程覆蓋。我沒有聽說過他們(我仍然在Rails 3.x上)。放輕鬆! – Mick

+0

這就是我提供這兩種解決方案的原因。 :) @MickSharpe – codyeatworld

+0

非常感謝!有效!我並不完全相信我明白爲什麼這樣做會發揮它的作用,但我相信隨着我繼續前進,我會弄清楚。 –

0

當您在日誌中查看時,它清楚地表明我沒有呈現任何視圖。

No template found for PostsController#create, rendering head :no_content 

所以PostsController#create行動,我們需要重定向到任何行動,主要是我們重定向到顯示操作。因此,您需要在創建操作中添加以下行。

# redirects user to show page of newly created post. 
if @post.save 
redirect_to @post 
else 
render 'new' 
end 

再去殺波:)