-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'
欣赏的任何想法。
感谢
感谢詹姆斯。我添加了多部分并添加了if条件来查看@ post.save是否为true。现在,当我尝试提交时出现错误。使用{:locale => [:en],:formats => [:html],:variants => [],:handlers => [:erb,:builder,:raw, :ruby,:coffee,:jbuilder]}。 – mogoli
<%= simple_form_for @post,html:{multipart:true} do | f | %> <%= f.input:image%> <%= f.input:caption%> <%= f.button:submit%> <% end %> – mogoli
您需要仔细阅读教程。如果保存,则重定向到帖子页面,如果不是,则该操作应呈现视图(通常是“新”模板)。 –