Add attachment mail rails

To add attachment support to a Rails application, you can use the carrierwave gem. Here's a step-by-step guide:

Step 1: Add the carrierwave gem to your Gemfile

In your Gemfile, add the following line:

gem 'carrierwave', '~> 2.1'

Then, run bundle install to install the gem.

Step 2: Create a uploader class

Create a new file in the app/uploaders directory, e.g., image_uploader.rb. This file will define the uploader class that will handle the attachment.

# app/uploaders/image_uploader.rb
class ImageUploader < CarrierWave::Uploader::Base
  process resize_to_fit: [1024, 1024]

  storage :file
end

In this example, we're defining an ImageUploader class that will resize the uploaded image to fit within a 1024x1024 pixel box.

Step 3: Add the uploader to your model

In your model, e.g., User, add the uploader as an attribute:

# app/models/user.rb
class User < ApplicationRecord
  mount_uploader :avatar, ImageUploader
end

In this example, we're adding an avatar attribute to the User model that will use the ImageUploader class.

Step 4: Update your form

In your form, add a file input field that will allow users to upload an attachment:

# app/views/users/_form.html.erb
<%= form_for @user, multipart: true do |form| %>
  <%= form.file_field :avatar %>
  <%= form.submit %>
<% end %>

In this example, we're adding a file input field to the form that will allow users to upload an attachment.

Step 5: Update your controller

In your controller, update the create action to save the uploaded attachment:

# app/controllers/users_controller.rb
class UsersController < ApplicationController
  def create
    @user = User.new(user_params)
    if @user.save
      redirect_to @user, notice: 'User created successfully'
    else
      render :new
    end
  end

  private

  def user_params
    params.require(:user).permit(:avatar)
  end
end

In this example, we're updating the create action to save the uploaded attachment to the User model.

Step 6: Display the attachment

In your view, you can display the uploaded attachment using the image_tag helper:

# app/views/users/show.html.erb
<%= image_tag @user.avatar %>

In this example, we're displaying the uploaded attachment as an image.

That's it! With these steps, you should now have attachment support in your Rails application using the carrierwave gem.