Rails中的表单不保存输入数据

时间:2018-04-10 02:26:05

标签: ruby-on-rails forms parameters

我在Rails应用程序中有一个表单没有保存输入数据。似乎有些东西我不知道但我不知道是什么。

控制器如下所示:

   def new
      @blog_post = BlogPost.new
   end

   def create
      @blog_post = BlogPost.new(blog_post_params)
       if @blog_post.save
       redirect_to @blog_post_path
     end
   end

   def blog_post_params
     params.require(:blog_post).permit(:title, :blurb, :content, :image)
   end
 end

这样的形式:

<form class="form-horizontal">
    <%= form_for (@blog_post) do |b| %>
    <%= b.text_field :title, placeholder: :title, class: "form-control" %><br>
    <%= b.text_field :blurb, placeholder: :blurb, class: "form-control" %><br>
    <%= b.text_area :content, placeholder: :content, class: "form-control" %> 
<div class="field">
    <%= b.file_field :image %></div><br>
    <%= b.submit ("Submit"), class: "btn btn-primary" %>
    <% end %>
</form>

我尚未添加上传者,但我认为这不应该有任何区别。我还从控制台向模型添加了数据,这将显示在我的索引页面中。所以似乎数据只是没有保存在表格中 - 但我不知道为什么会这样。对能够提供帮助的人表示非常感谢: - )

修改

服务器日志如下所示:

Started GET "/blog_posts/new? 
utf8=%E2%9C%93&authenticity_token=2IuVGQaet%2Bsi2GU57Ukrvit83HVyYely1Tw 
RqDnYZvFAWpGQm7uVCrOvM70BJd82UNy3a5XfUtGl9Lz21Lzb5A%3D%3D&blog_post%5Btitle% 
5D=asd&blog_post%5Bblurb%5D=asdf&blog_post%5Bcontent%5D=asdfg&blog_post%5Bimag 
e%5D=&commit=Submit" for 127.0.0.1 at 2018-04-10 10:37:18 +0800
Processing by BlogPostsController#new as HTML
Parameters: {"utf8"=>"✓", 
"authenticity_token"=>"2IuVGQaet+si2GU57Ukrvit83HVyYely1TwRqDnYZvFAWpGQm7uVCr 
OvM70BJd82UNy3a5XfUtGl9Lz21Lzb5A==", "blog_post"=>{"title"=>"asd", 
"blurb"=>"asdf", "content"=>"asdfg", "image"=>""}, "commit"=>"Submit"}
Rendering blog_posts/new.html.erb within layouts/application
Rendered shared/_navbar.html.erb (1.1ms)
Rendered blog_posts/new.html.erb within layouts/application (6.1ms)
Rendered shared/_footer.html.erb (0.5ms)
Completed 200 OK in 34ms (Views: 31.8ms | ActiveRecord: 0.0ms)

和索引:

Started GET "/blog_posts" for 127.0.0.1 at 2018-04-10 10:52:07 +0800
Processing by BlogPostsController#index as HTML
  Rendering blog_posts/index.html.erb within layouts/application
  Rendered shared/_navbar.html.erb (0.7ms)
  BlogPost Load (0.2ms)  SELECT "blog_posts".* FROM "blog_posts"
  Rendered blog_posts/index.html.erb within layouts/application (3.5ms)
  Rendered shared/_footer.html.erb (0.3ms)
Completed 200 OK in 27ms (Views: 24.5ms | ActiveRecord: 0.2ms)

1 个答案:

答案 0 :(得分:-1)

您的表单不正确。这里是修改后的表格

    <%= form_for (@blog_post, :html => { class: "form-control" }) do |b| %>
     <%= b.text_field :title, placeholder: :title, class: "form-control" %><br>
     <%= b.text_field :blurb, placeholder: :blurb, class: "form-control" %><br>
     <%= b.text_area :content, placeholder: :content, class: "form-control" %> 
     <div class="field">
     <%= b.file_field :image %></div><br>
      <%= b.submit ("Submit"), class: "btn btn-primary" %>
    <% end %>

希望它能够奏效。