我是 Rails 新手,一直在关注 YouTube https://www.youtube.com/watch?v=70Pu_28yvdI上的教程,已经到了第 40 分钟左右,当我尝试创建新帖子并附上图片时,我得到了错误图像的扩展名与其内容不匹配,我编写了与他完全相同的代码并不断收到错误。非常感谢你的帮助。
post.rb 文件
class Post < ActiveRecord::Base
belongs_to :user
has_attached_file :image, styles: { medium: "700x500#", small: "350x250" }
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
end
post_controller.rb 文件
class PostsController < ApplicationController
before_action :find_post, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def index
@post = Post.all.order("created_at DESC")
end
def show
end
def new
@post = current_user.posts.build
end
def create
@post = current_user.posts.build(post_params)
if @post.save
redirect_to @post
else
render 'new'
end
end
def edit
end
def update
if @post.update(post_params)
redirect_to @post
else
render 'edit'
end
end
def destroy
@post.destroy
redirect_to root_path
end
private
def find_post
@post = Post.find(params[:id])
end
def post_params
params.require(:post).permit(:title, :link, :description, :image)
end
end
20150728130528_add_attachment_image_to_posts.rb 文件
class AddAttachmentImageToPosts < ActiveRecord::Migration
def self.up
change_table :posts do |t|
t.attachment :image
end
end
def self.down
remove_attachment :posts, :image
end
end