In this application I am trying to do image upload. When I run the migration I am getting error.
Controller:
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
Model:
class Post < ActiveRecord::Base
has_attached_file :image
validates_attachment_content_type :image, :content_type => ["image/jpg",
"image/jpeg", "image/png", "image/gif"]
end
Migration:
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 %>
Routes:
Rails.application.routes.draw do
resources :posts
get 'post/:id' => 'post#show'
end
Error in console:
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_attachmentis a helper method provided bypaperclipgem to add columns which would containfile_name,content_type,file_sizeof the attachment.As your error states, Rails has no idea on what this method means when you call it in your migration file:
The most obvious reason for this behaviour is that you did not require
paperclipgem properly. Refer to its installation section on github and don't forget to runbundle installbefore usage.