在此應用中,我試圖做的圖片上傳。當我運行遷移時出現錯誤。NoMethodError:對#未定義的方法`add_attachment <AddImageCloumnToPost:將0x58 ba1b8>
控制器:
class PostsController < ApplicationController
def index
end
def new
@post = Post.new
end
def
@post = Post.new(post_params)
@post.save
end
def show
@post=Post.find(params[:id])
end
def edit
end
def delete
end
def post_params
params.require(:post).permit(:image)
end
end
型號:
class Post < ActiveRecord::Base
has_attached_file :image
validates_attachment_content_type :image, :content_type => ["image/jpg",
"image/jpeg", "image/png", "image/gif"]
end
遷移:
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.timestamps null: false
end
end
end
class AddImageCloumnToPost < ActiveRecord::Migration
def up
add_attachment :posts, :image
end
def down
remove_attachment :posts, :image
end
end
new.html.erb:
<h1>Posts#new</h1>
<%= form_for(@post, :html=>{ :multipart => true }) do |f| %>
<%= f.label :image %>
<%= f.file_field :image %>
<%= f.submit "Upload" %>
<% end %>
show.html.erb:
<h1>Posts#Show</h1>
<%= image_tag @post.image.url %>
條路線:
Rails.application.routes.draw do
resources :posts
get 'post/:id' => 'post#show'
end
錯誤在控制檯:
D:\imageupload>rake db:migrate
DL is deprecated, please use Fiddle
== 20150608132353 CreatePosts: migrating ======================================
-- create_table(:posts)
-> 0.0491s
== 20150608132353 CreatePosts: migrated (0.0491s) =============================
== 20150608132858 AddImageCloumnToPost: migrating =============================
-- add_attachment(:posts, :image)
rake aborted!
StandardError: An error has occurred, all later migrations canceled:
undefined method `add_attachment' for #<AddImageCloumnToPost:0x58ba1b8>D:/imageupload/db/migrate/20150608132858_add_image_cloumn_to_post.rb:3:in `up'
C:in `migrate'
NoMethodError: undefined method `add_attachment' for #<AddImageCloumnToPost:0x58
ba1b8>
D:/imageupload/db/migrate/20150608132858_add_image_cloumn_to_post.rb:3:in `up'
C:in `migrate'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
不知道你需要發佈您的整個代碼這一點。該錯誤似乎是在您的遷移過程中,它無法識別「add_attachment」。 – Shadwell
運行'耙分貝:遷移--trace'更好地理解錯誤 – Abhi
好吧,我會檢查... – User333