2016-05-12 34 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

您需要仔細閱讀教程。如果保存,則重定向到帖子頁面,如果不是,則該操作應呈現視圖(通常是「新」模板)。 –

相關問題