2016-09-01 64 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 

再去杀波:)