Rails 上传图片

1.新建一个项目

    rails new avatar

2.在项目的Gemfile中添加:

gem 'carrierwave'  
gem 'mini_magick'  

3.建立一个model

  rails g model user name:string email:string

4.建一个controller

  rails g controller users

5.为users表添加一个avatar字段

  rails g migration add_avatar_to_users avatar:string

6.rake db:migrate

7.生成Avatar

 rails generate uploader Avatar #将会生成文件app/uploaders/avatar_uploader.rb

8.为user的model user.rb添加如下代码,使表之间关联

 mount_uploader :avatar, AvatarUploader

9.接下来进行修改app/uploaders/avatar_uploader.rb

# encoding: utf-8

class AvatarUploader < CarrierWave::Uploader::Base

  # Choose what kind of storage to use for this uploader: 
  storage :file
  # storage :fog

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir  #定义上传到哪个文件夹下    
  "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"  
  end  

  def default_url  #可以定义默认图片,如过用户没有上传图片,则可以使用默认的图片    "avatar/#{version_name}.png"  
  end

  # Add a white list of extensions which are allowed to be uploaded.
  # For images you might use something like this:
  def extension_white_list    
  %w(jpg jpeg gif png)   
  end  

10.添加routes

  resources :users

11.在user_controller.rb中

 def index
        @users = User.all
    end

    def new
        @user = User.new
    end

    def create
        @user = User.new(user_params)
        @user.save
        redirect_to user_index_path
    end


    # def update
    #     @user = User.find(params[:id])
    #     @user.update(user_params)
    #     redirect_to user_path
    # end

    private
        def user_params
            params.require(:user).permit(:name,:email,:avatar)
        end
end

12.views/user/

index.html.erb

<% @users.each do |user| %>
  <%= user.name%>
  <%= image_tag user.avatar_url if user.avatar %>
<%end %>


new.html.erb
<%= form_for @user, :url=>user_index_path do |f| %>
  <div class="field">
    <%= f.label :name %>
    <%= f.text_field :name %><hr/>
    <%= f.file_field :avatar %>
    <%= f.hidden_field :avatar_cache %>
  div><hr/>
  <%= f.submit %>
<%end%>

你可能感兴趣的:(Ruby,On,Rails)