Kundan Sinha Kundan Sinha - 3 months ago 14
Ruby Question

How to upload image in ruby app folder and insert url in database column


Controller

Save the object




How to Use This Controller to insert image in any folder and image url store in database

def create_json


@user = User.new(userFirstName: params[:userFirstName], userLastName: params[:userLastName], userEmail: params[:userEmail], password: encrypted_password, userImage: params[:userImage])
if @user.save #if save succeeds, redirect to the index action
redirect_to(:action => 'show', id: User.last.id)
else
#if not succeeds, redirect to the index action
redirect_to(:action => 'new')
end end

Answer

User(Model) mount_uploader :userImage, AvatarUploader

UsersController -> @user = User.new(user_params)
                    if @user.save
                     redirect_to(:action => 'show', id: User.last.id)
                    else
                    render :json => data_hash2, :content_type => 'application/json' 
                    end



class AvatarUploader < CarrierWave::Uploader::Base
storage :file
def store_dir
        "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
    end
def extension_white_list
        %w(jpg jpeg gif png) 
    end  end

If You Using Web Service

<form action="http://ruby/controllername/create" lass="new_user" id="new_user" enctype="multipart/form-data" accept-charset="UTF-8" method="post">