2016-05-12 35 views
-1

Im遵循本教程:https://www.devwalks.com/lets-build-instagram-in-rails-part-1/模型在rails上返回数据ruby没有数据ruby

创建一个instagram版本。当我上传图片时,添加一个标题并提交,它将按照预期重定向到索引页面,但数据似乎没有保存。当我打开rails控制台并尝试使用Posts.first获取帖子时,它返回nil。

控制器:

class PostsController < ApplicationController 

    def index 

    end 

    def new 
     @post = Post.new 
    end 

    def create 
     @post =Post.create(post_params) 
     @post.save 
     redirect_to posts_path 

    end 

    private 

    def post_params 
     params.require(:post).permit(:image, :caption) 
    end 

end 

型号:

class Post < ActiveRecord::Base 
    validates :image, presence: true 
    has_attached_file :image, styles: { :medium => "640x"} 
    validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/ 
end 

form: 

<%= simple_form_for @post do |f| %> 
    <%= f.input :image %> 
    <%= f.input :caption %> 
    <%= f.button :submit %> 
<% end %> 

routes: 

resources :posts 
    root 'posts#index' 

欣赏的任何想法。

感谢

回答

1

我在这里看到了几个问题:

  1. create将节省,所以你不需要再@post.save
  2. create返回新的Post对象,但是您必须检查它是否已成功保存(通过@post.persisted或通过if @post.save)。
  3. 从1 & 2,我相信您的文章没有保存,由于图像存在验证。
  4. 现在为什么发生这种情况?我想你的表格没有multipart/form-data设置图像文件根本没有提交。

要添加到simple_form(paperclip README):

<%= simple_form_for @post, html: { multipart: true } do |f| %> 
+0

感谢詹姆斯。我添加了多部分并添加了if条件来查看@ post.save是否为true。现在,当我尝试提交时出现错误。使用{:locale => [:en],:formats => [:html],:variants => [],:handlers => [:erb,:builder,:raw, :ruby,:coffee,:jbuilder]}。 – mogoli

+0

<%= simple_form_for @post,html:{multipart:true} do | f | %> <%= f.input:image%> <%= f.input:caption%> <%= f.button:submit%> <% end %> – mogoli

+0

您需要仔细阅读教程。如果保存,则重定向到帖子页面,如果不是,则该操作应呈现视图(通常是“新”模板)。 –

相关问题